I'm using Sanic with a database, and I'd like to store the db engine and session creator with the app object, so anywhere I have the app I can get the db. Is there any supported way to attach my own data to a Sanic app object? Right now I'm just doing this when creating my app:
def setup_database(app: Sanic):
db = init_db(app)
app.db = db
but it seems questionable to just add a 'db' object to the app because in future Sanic could define that attribute.
No, there is no supported way to do this, and no shared application context like you'd find in Flask or pylons.
This is a big problem for plugin authors, because quite often plugins need to store context per-application and per-request.
To address this, I created Sanic Plugins Framework. It adds this feature (and a few others) to sanic.
Its aimed at plugin developers, but it might be able to help you out.
@garyo you can try contextvars (in the upcoming Python 3.7) or something bound to the current asyncio.Task, like the backport of contextvars, but is does not provide support for asyncio just yet; aiocontextvars that covers some of the contextvars functionality and will be deprecated when the contextvars backport comes out or even aiotask-context that enables some level of context in async applications. To create your own context bound to asyncio.Task, you can take a look at this snippet from sanic-jwt project (and yes, I created that code but I just referenced it because it's quite simple to implement, actually) :wink:
@vltr thanks contextvars works well in 3.7, imo the request could be realised as such or could contain some convenience functionality to deliver a shared contextvars (imho)
@cinatic yes, I agree with you. But, since Sanic aims for Python 3.5+, we can't use contextvars for it. Now, if you want a simple way of storing shared data (in the request context), you can use the Request object itself, since it is a dict:
# in the middleware
request["hello"] = "world"
# in the handler
assert request["hello"] == "world"
:wink:
@vltr oh okay well that's super easy... thanks for the hint
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is incorrect, please respond with an update. Thank you for your contributions.
Most helpful comment
@vltr thanks contextvars works well in 3.7, imo the request could be realised as such or could contain some convenience functionality to deliver a shared contextvars (imho)