9

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.

msvalkon
  • 11,887
  • 2
  • 42
  • 38
John
  • 3,037
  • 8
  • 36
  • 68

1 Answers1

11

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()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • That's great. Any way to do it the second way without having to wait for the first request? I would like to be compatible with WSGI servers as well. – John Jun 16 '14 at 20:14
  • This answer was helpful too: http://stackoverflow.com/questions/9449101/how-to-stop-flask-from-initialising-twice-in-debug-mode. – John Jun 16 '14 at 20:28
  • 1
    @Anonymous: clarified some more. – Martijn Pieters Jun 16 '14 at 20:31
  • I had been using debug=True and for some reason unknown to me, that reloads everything twice unless explicitly specified as in the linked question. – John Jun 16 '14 at 20:39