Skip to content

How to share a httpx.AsyncClient() across the app? #1549

Answered by provinzkraut
danechitoaie asked this question in Q&A
Discussion options

You must be logged in to vote

and I've read in their docs it's more optimal to have a single client that you share across the app

I am not aware of this. However, there's nothing preventing you from doing that. You can just create an instance of the client and then import that.

If you want something that's specifically bound to the lifetime of the application, you could of course use application state, dependency injection and the lifetime hooks.

from litestar import Litestar
from litestar.datastructures import State
from litestar.di import Provide
from httpx import AsyncClient


def on_startup(state: State) -> None:
  state.client = AsyncClient()


async def on_shutdown(state: State) -> None:
  await state.client.a…

Replies: 2 comments 1 reply

Comment options

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

Answer selected by danechitoaie
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
3 participants