Flask: Creating objects that remain over multiple requests

Question:

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.

Asked By: John

||

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()
Answered By: Martijn Pieters

Update the answer written by Martijn Pieters.

before_first_request() has been deprecated since Flask 2.2 and will be removed in Flask 2.3. It’s suggested to "Run setup code while creating the application instead."

Answered By: powerful_clouds
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.