Skip to content

How to manage setup/teardown of resources in async views? #4163

Answered by miguelgrinberg
wgwz asked this question in Q&A
Discussion options

You must be logged in to vote

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:

@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 g.session to send your request:

# ...
weather_report = await fetch_weather(g.session, lat, lon)
# ...

Finally, an teardown_request handler does the cleanup:

@app.teardown_request
async def teardown(exc):
    await g.session.close()

Replies: 1 comment 9 replies

Comment options

You must be logged in to vote
9 replies
@wgwz
Comment options

@miguelgrinberg
Comment options

@miguelgrinberg
Comment options

@davidism
Comment options

@nioncode
Comment options

Answer selected by wgwz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants