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.

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)