Looking for an example. Please help

Check this tutorial: https://towardsdatascience.com/build-an-async-python-service-with-fastapi-sqlalchemy-196d8792fa08

at the end there is a section just before conclusion,

from fastapi import Depends
async def create_book(..., book_dal: BookDAL = Depends(get_book_dal)):
    return await book_dal.create_book(...)

This Depeneds, how can i do this Sanic.

I know it is posssible from,

But i just can’t connect the dots.

async def foo(*_):
    print('ENTER !!!!!!!!!!!')
    yield 'bar'
    print('EXIT !!!!!!!!!!!!')


I have no idea what’s happening.

Please if possible, provide an real world example like that tutorial with, “injection+sqlalchemy+context(app+request)”


You have a couple options.

  1. The higher-level app.ext.dependency is meant to take an object instance. It will inject that instance into your handler.
async def setup_db_client(app):
    db_client = DBClient(...)
  1. The lower-level app.ext.add_dependency takes a callable that optionally has a Request and can be used to build request-bound objects. Let’s say instead of having a DBClient that persisted the lifetime of your application, you wanted to create a long-lived connection pool and a client per request (to keep state on it for example).
async def setup_db_client(request: Request, db_pool: DBPool) -> DBClient:
    db_client = DBClient(db_pool)
    db_client.request_id = request.id
    return db_client

async def setup_db_pool(app):
    db_pool = DBPool(...)
    app.ctx.add_dependency(DBClient, setup_db_client)

There is more information with some examples here: Dependency Injection | Sanic Framework