pythonpython-asyncioaiohttpquart

aiohttp.ClientSession() in Quart


How can I create an aiohttp.ClientSession() once so that I can use it when a request is received? And I'd like to deploy this later with Gunicorn as well.


Solution

  • You can use a startup function via the before_serving decorator,

    @app.before_serving
    async def startup():
        app.client = aiohttp.ClientSession()
    
    @app.get("/")
    async def index():
        await app.client.get(...)
    

    As Quart is a ASGI framework you'll need to use an ASGI server such as Hypercorn rather than Gunicorn (a WSGI server).