【发布时间】:2023-04-09 15:43:01
【问题描述】:
from aiohttp import web
from aiohttp import ClientSession
# this would go in a different file but keep it simple for now
class Generate:
# Get a person object from my website
async def get_person(self):
async with ClientSession() as session:
async with session.get('http://surveycodebot.com/person/generate') as response:
resp = await response.json()
# this prints the person
print(resp)
return resp
# loops `get_person` to get more than 1 person
async def get_people(self):
# array for gathering all responses
for _ in range(0,10):
resp = await self.get_person()
return resp
# class to handle '/'
class HomePage(web.View):
async def get(self):
# initiate the Generate class and call get_people
await Generate().get_people()
return web.Response(text="Hello, world")
if __name__ == "__main__":
app = web.Application()
app.router.add_get('/', HomePage)
web.run_app(app)
代码有效,一切都很好。我想知道为什么HomePage 需要一段时间才能加载。我认为我应该在第 28 行使用 yield,但是当我这样做时它会出错。谢谢。
【问题讨论】:
-
看起来如果我将 url 更改为另一台服务器,它的工作速度会更快。看起来代码需要优化发出 Get 请求的服务器代码。即将
http://surveycodebot.com/person/generate更改为https://jsonplaceholder.typicode.com/posts如果有优化的方法,请告诉我。
标签: python python-3.x async-await python-asyncio aiohttp