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?
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.
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.
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 .
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.
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