Python 3 aiohttp |优化服务器响应时间

时间:2017-06-11 05:18:08

标签: python python-3.x async-await python-asyncio aiohttp

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,但是当我这样做时它就会变成barfs。感谢。

1 个答案:

答案 0 :(得分:0)

您可以通过aiohttp on_startup信号在多个客户端请求之间共享会话来进行优化。

如下所示:

import asyncio
from aiohttp import web
from aiohttp import ClientSession


class Generate:

    def __init__(self, session):
        self.session = session

    # Get a person object from my website
    async def get_person(self):
        async with self.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 app['generate'].get_people()
        return web.Response(text="Hello, world")


async def on_startup(app):
    session = ClientSession()
    app['generate'] = Generate(session)



if __name__ == "__main__":
    app = web.Application()
    app.router.add_get('/', HomePage)
    app.on_startup.append(on_startup)
    web.run_app(app)