Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a file on initialization in a flask application

I have a big file, let's call it machine_learning_model.hdf5. I am loading it into my application every time a post request endpoint is hit. The pseudocode looks like this:

def post(self):
  model = load_model('./machine_learning_model.hdf5')
  return( model.predict())

However the fact that I am loading the file every time the endpoint is hit causing problems. In general, what is the proper way to load a big file into a flask application on initialization so the individual endpoints can use the code from said file.

like image 628
Embedded_Mugs Avatar asked Nov 05 '18 21:11

Embedded_Mugs


People also ask

What does __ init __ py do in flask?

the Flask application object creation has to be in the __init__.py file. That way each module can import it safely and the __name__ variable will resolve to the correct package. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__.py file.


1 Answers

You can load it on application startup and bind to a flask application object:

# app.py
app = Flask(__name__)
app.some_model = load_model('./machine_learning_model.hdf5')

# handlers.py
from flask import current_app

def post(self):
    return current_app.some_model.predict()
like image 74
Fine Avatar answered Sep 21 '22 20:09

Fine