Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Creating objects that remain over multiple requests

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.

like image 318
John Avatar asked Jun 16 '14 20:06

John


Video Answer


1 Answers

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()
like image 59
Martijn Pieters Avatar answered Oct 19 '22 03:10

Martijn Pieters