Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a variable into `g` once and only once for application in Flask

Tags:

python

flask

web

I want to save an object which is the result of a expensive function. The expensive function should only be processed once before any request.

I checked the document of Flask and considered about g for saving the result and @app.before_first_request decorator to define this assignment happended only once.

My codes are like this:

@app.before_first_request
def before_first_request():
    g.rec = take_long_time_to_do()

@app.route('/test/')
def test():
    return render_template('index.html',var_rec=g.rec)

However, these codes won't work well. It works only in the first time test request is called. When I access "myapplication/test" second time, the g.rec doesn't exist, which will throw an exception

Does anyone have ideas about how to assign a global variable into g when initing the application?

like image 690
Hanfei Sun Avatar asked Jan 04 '13 06:01

Hanfei Sun


People also ask

What is the difference between G variable and session in the Flask?

session gives you a place to store data per specific browser. As a user of your Flask app, using a specific browser, returns for more requests, the session data is carried over across those requests. g on the other hand is data shared between different parts of your code base within one request cycle.

What is the use of G in Flask?

g is an object for storing data during the application context of a running Flask web app. g can also be imported directly from the flask module instead of flask. globals , so you will often see that shortcut in example code.

Which two are the default addresses of a Flask website?

Flask launches its built-in developmental web server and starts the webapp. You can access the webapp from a browser via URL http://127.0.0.1:5000 (or http://localhost:5000 ). The webapp shall display the hello-world message. You can stop the server by pressing Ctrl-C .


1 Answers

g is the global object for that request only. Have you considered using a caching mechanism?

> pip search flask | grep "cache" | sort
Flask-Cache               - Adds cache support to your Flask application
Flask-Cache-PyLibMC       - PyLibMC cache for Flask-Cache, supports multiple operations
Flask-Memsessions         - A simple extension to drop in memcached session support for Flask.

Then you can store the result of take_long_time_to_do() there and retrieve it if it exists.

like image 97
sberry Avatar answered Sep 16 '22 23:09

sberry