Skip to content

Using one session in FastAPI #7760

Closed Answered by Dreamsorcerer
diamond-fish asked this question in Q&A
Discussion options

You must be logged in to vote

That's fine. My only suggestion would be to avoid a singleton (and save yourself the wrapper code). In aiohttp, we'd use cleanup_ctx (same thing as lifespan in FastAPI/Starlette) and just save it to the app object:

client = web.AppKey("client", ClientSession)

async def client_session(app: web.Application) -> None:
    async with ClientSession() as sess:
        app[client] = sess
        yield

app.cleanup_ctx.append(client_session)

The you'd be able to use it in any handler like async with request.app[client].get(...) as resp:.

You can do something similar with FastAPI, but it won't be typed. Or, you can use their dependency injection stuff to make it typed (though I personally think i…

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@Dreamsorcerer
Comment options

Answer selected by diamond-fish
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants