How to manage setup/teardown of resources in async views? #4163
-
Is it possible to attach an async resource that requires setup/teardown operations to i.e. The The flask docs have shown ways of dealing with this for database connections. Is there an idiomatic way to do this with the new async view function support? Here's a small example that shows a bit of the issue:
It'd be nice if I could pass the Suggestions/discussion appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
Hi Kyle! Interesting problem. I think you should be able to put the aiohttp session in First, in a @app.before_request
async def before():
g.session = aiohttp.ClientSession(
headers=[("User-Agent", "Kyle Lawlor - spacestationbot")],
raise_for_status=True,
) Then in your request you can use # ...
weather_report = await fetch_weather(g.session, lat, lon)
# ... Finally, an @app.teardown_request
async def teardown(exc):
await g.session.close() |
Beta Was this translation helpful? Give feedback.
Hi Kyle!
Interesting problem. I think you should be able to put the aiohttp session in
flask.g
. I'm writing this from memory, so you'll need to test it, but I think this should work.First, in a
before_request
handler you create the session:Then in your request you can use
g.session
to send your request:Finally, an
teardown_request
handler does the cleanup: