I've been able to create objects that are created at every request from this link: http://flask.pocoo.org/docs/appcontext/#locality-of-the-context.
I'm actually creating an API based off of http://blog.miguelgrinberg.com/post/designing-a-restful-api-using-flask-restful.
I want to be able to load an object once and just have it return a processed response rather than it loading at every request. The object is not a DB, just requires unpickling a large file.
I've looked through the documentation, but I'm still confused about this whole Flask two states thing.
The Flask contexts only apply per request. Use a module global to store data you only want to load once.
You could just load the data on startup, as a global:
some_global_name = load_data_from_pickle()
WSGI servers that support multiple processes either fork the process, or start a new Python interpreter as needed. When forking, globals are copied to the child process.
You can also use before_first_request()
hook to load that data into your process; this is only called if the process has to handle an actual request. This would be after the process fork, giving your child process unique data:
@app.before_first_request
def load_global_data():
global some_global_name
some_global_name = load_data_from_pickle()
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