How to share db pool/session data between multiple requests?

up to today I’ve used BottlePy + psycopg2 for my website, but I’d like to move from that to Sanic + asyncpg.

Is there something equivalent to Vibora components (, or bottlepy plugins (

I could just use middlewares, and add db and session to the request (a simple request.db = pgpool) but since session has a bit of overhead (have to execute some queries) i would like to only pass it to the routes that need it.

@edoardoc Why not add it to the app instead? By utilize the before_server_start, you can add the connection pool to the app.

async def before_server_start(app, loop):
    config = app.config["DB_CONFIG"]
    # Config for Mysql Connection
    config["db"] = config["database"]
    app.db = await ConnectionPool(loop=loop, trace=True).init(app.config["DB_CONFIG"])

If I understand your question right, you can refer this demo project that I’m currently working.

I cannot add to app because I’m using blueprints, and blueprints don’t have access to the app.

check to get access to the app.db

even you use Blueprint I think you still can access the app within request.

Thanks guys, i didn’t know about that.
How about the function in bottlepy where handlers get passed objects depending if they have specific keywords in their arguments? This could be, again, handy for routes that need components that sometimes have some overhead to get.

For example, log_out_user(request, session) would have session passed to it automatically.