Is there such thing as application-scope python variables in Flask? I'd like to implement some primitive messaging between users, and shared data cache. Of course, it is possible to implement this via a database, but I wanted to know maybe there is a db-free and perhaps faster approach. Ideally, if the shared variable would be a live python object, but my needs would be satisfied with strings and ints, too.
Edit: complemented with (non-working) example
from flask import g
@app.route('/store/<name>')
def view_hello(name=None):
g.name = name
return "Storing " + g.name
@app.route("/retrieve")
def view_listen():
n = g.name
return "Retrieved: " + n
At trying to retrieve g.name, this triggers error: AttributeError: '_RequestGlobals' object has no attribute 'name'
The application context is a good place to store common data during a request or CLI command. Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context.
Flask is a lightweight Python web framework that provides useful tools and features for creating web applications in the Python Language. It gives developers flexibility and is an accessible framework for new developers because you can build a web application quickly using only a single Python file.
To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments. Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.
Flask code has to be thread-safe, also called re-entrant. Local variables and parameters are always thread-safe.
I'm unsure whether this is a good idea or not, but I've been using this to share data easily between requests:
class MyServer(Flask):
def __init__(self, *args, **kwargs):
super(MyServer, self).__init__(*args, **kwargs)
#instanciate your variables here
self.messages = []
app = MyServer(__name__)
@app.route("/")
def foo():
app.messages.append("message")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With