Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application-scope variables in Flask?

Tags:

python

flask

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'

like image 893
Passiday Avatar asked May 09 '13 19:05

Passiday


People also ask

What is the application context in Flask?

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.

What are the applications of Flask?

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.

Can you use global variables in Flask?

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.

Are flasks Threadsafe?

Flask code has to be thread-safe, also called re-entrant. Local variables and parameters are always thread-safe.


1 Answers

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")
like image 79
t.animal Avatar answered Nov 03 '22 09:11

t.animal