What is the best way to store globally accessible "heavy" objects?
See original GitHub issueIn Flask we have a g
global context to keep the global variables of the request. A kind of canonical example from the docs:
from flask import g
def get_db():
if 'db' not in g:
g.db = connect_to_database()
return g.db
@app.teardown_appcontext
def teardown_db():
db = g.pop('db', None)
if db is not None:
db.close()
So I wonder if there is something similar in starlette
? I have a couple of very weighty objects which I don’t want to initialize too often. These objects are “read-only” and are not modified during app’s lifetime. What is the best way to handle cases like this?
Issue Analytics
- State:
- Created 5 years ago
- Comments:12 (4 by maintainers)
Top Results From Across the Web
What is the best way to store global objects with NodeJS and ...
Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
Read more >Using Multidimensional Storage (Globals)
Storing Data in Global Nodes ... To store a value within a global subscript node, simply set the value of the global node...
Read more >How do you guys manage "global" state? : r/cpp - Reddit
You're probably right, but not because it offers nothing over a global. You can control access patterns, construction timing, etc... and these ...
Read more >Why is Global State so Evil?
Function parameters - often overlooked, but parameterising your functions better is often the best way to avoid global state.
Read more >Introduction to Azure Blob storage - Microsoft Learn
A storage account provides a unique namespace in Azure for your data. Every object that you store in Azure Storage has an address...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Depends on if you’re asking about “during app’s lifetime” or “during the request/response cycle”.
(Flask’s
g
object is for storing data associated with the current request/response cycle.)For stuff that has a request/response lifespan, you can store arbitrary stuff on the request “scope”.
request["foo"] = whatever()
.For lifespan, use globals, with
@app.on_event('startup')
/@app.on_event('shutdown')
to setup and teardown any network connections or other resources.Happy to dig further into any specific questions around this too. (And consider if we end up wanting any helpers for task-local context)