Hi,
I am trying to pass a db connection objection to all my routes (on demand) and my first guess would be an equivalent of current_app object like we do in flask.
I have seen issues #226 and #374 discussing similar concerns but I am not sure if there is any definite way to do it. And by saying definite I mean to not break our universe in a future version (potentially v1.0.0)
I would say request['app'] is very intriguing to use but I would like to know your thoughts first
Cheers,
Periklis
Passing a database instance that's declared once, globally, will do what you need here.
Have a look over https://www.starlette.io/database/
This example service that I'm building out also takes the same approach, so might be a good place to look.
There's no particular need to attach it to the app, or the request - declare it in one place in the codebase, then import and use it.
Thanks for the answer @tomchristie
Is the databases module the only way? I need to work with mongo and it doesn't seem to be supported.
What are some other patterns used with Starlette for that?
Thanks again
I think what you're looking for is request.state.
You can include a middleware class that attaches a mongo connection instance (or whatever else) to the request, which will then be available anywhere you're passing the request around.
If you need that to work lazily, then you'd need the object that you're attaching to deal with only acquiring the connection at the first point it's actually used.
I like that approach. I will most probably go with it :) Thanks again
Most helpful comment
I think what you're looking for is
request.state.You can include a middleware class that attaches a mongo connection instance (or whatever else) to the request, which will then be available anywhere you're passing the request around.
If you need that to work lazily, then you'd need the object that you're attaching to deal with only acquiring the connection at the first point it's actually used.