Async dependencies? #9460
-
|
Hi there, I have found synchronous dependencies very easy to deal with @lru_cache()
def get_client() -> Client:
return Client( ... )
@app.get('/')
async def my_endpoint(client: Annotated[Client, Depends(get_client)]) -> dict[str, any] :
data = await client.fetch()
return dataBut I have found asynchronous much more convoluted to deal with This flat out doesn't work @lru_cache()
async def get_connection() -> Connection:
client = await AsyncClient.connection( ... )
return client
@app.get('/')
async def my_endpoint(client: Annotated[Connection, Depends(get_connection)]) -> dict[str, any] :
data = await client.fetch() # AttributeError: 'coroutine' object has no attribute 'fetch'
return dataYou have to resort to an untyped storage on app state async def get_connection() -> Connection:
client = await AsyncClient.connection( ... )
return client
@app.startup()
async def setup_connection() -> Connection:
app.state.connection = await get_connection()
@app.get('/')
async def my_endpoint(request: Request) -> dict[str, any] :
connection: Connection = request.app.state.connection
data = await client.fetch()
return dataIs there a well accepted general solution / standard procedure for dealing with async deps? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
Here is how I did it 6 months ago (I am not sure if things have changed since then) |
Beta Was this translation helpful? Give feedback.
-
|
If you don't like approach with @lru_cache()
def _get_client() -> Client:
return Client( ... )
async def get_client_async() -> Client:
return _get_client()
@app.get('/')
async def my_endpoint(client: Annotated[Client, Depends(get_client_async)]) -> dict[str, any] :
data = await client.fetch()
return data |
Beta Was this translation helpful? Give feedback.
If you don't like approach with
lifespanandrequest.state, you can wrap your cached dependency function withasyncfunction: