Bring DB Connection everywhere

Hi there!
I’ve been playing recently with Sanic and I really love it!

So far, I’ve always developed stuff with Java and the Spring suite. There, I’ve had the Data part which offered an easy and accesible way to query the database from anywhere.

Is there a way to do the same thing in Sanic?
From what I’ve understood, I might need everytime to register the database connection in the app instantiation and the blueprint’s one. Is this the way to do so?

I guess there are sort of different methodologies. You could start and stop a DB connection through Middleware. In this case you would attach the connection to the request.ctx.

Perhaps a better solution is to use listeners and attach your connection pool at startup and close it on shutdown.

What package are you using for connecting to your dB? I can throw together a snippet for you.

Take a look at the example in the docs. It probably is what you are looking for.

When you do this, you now can access that inside your view handlers on the request object.

request.app.db

So, ideally I was thinking of using PostgreSQL and MonngoDB as my databases.
I’ve read the docs, but there’s just one thing that I can’t understand: do I have to do that initialization only once or N times, depending on the number of Blueprints?

You should do it once on the entire app.

Thank you! Seems it is working. Thank you so much (y)

Hi @ahopkins ,
Can you please help to throw a snippet code that use connection pool ? I want to have a code which have :

  • Create connection pool and have listener attaching to it
  • Handler (using blueprint ) use database connection and return result.

Since there is a lot of information from the forum, so I dont know what is the best practice of using Database in Sanic Application.

If you are using Sanic Extensions, then this is the easiest way: Dependency Injection | Sanic Framework

class FakeConnection:
    async def execute(self, query: str, **arguments):
        return "result"


@app.before_server_start
async def setup_db(app, _):
    db_conn = FakeConnection()
    app.ext.dependency(db_conn)


@app.get("/")
async def handler(request, conn: FakeConnection):
    response = await conn.execute("...")
    return text(response)