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.
Asked
Active
Viewed 431 times
-2
-
Please provide enough code so others can better understand or reproduce the problem. – Community Mar 19 '22 at 03:57
1 Answers
1
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).

pgjones
- 6,044
- 1
- 14
- 12
-
Will it be created in the event loop and how will it close (as there isn't an explicit close) ? Just wondering based on https://docs.aiohttp.org/en/stable/faq.html#why-is-creating-a-clientsession-outside-of-an-event-loop-dangerous – yan-hic Jun 22 '22 at 14:18
-
Yep, before_serving functions are guaranteed to run in the correct event loop. You can use a after_serving to close. – pgjones Jun 22 '22 at 15:40
-
would you redeclare Quart to include `client` here ? `class Quart(Quart)` works but not sure if good practice. – yan-hic Nov 20 '22 at 20:52
-
1