I have a flask app that first of all loads a keras model and then executes the prediction function. According to this answer I save the tensorflow graph in a global variable and use the same graph for the prediction function.
def load_model():
load_model_from_file()
global graph
graph = tf.get_default_graph()
def predict():
with graph.as_default():
tagger = Tagger(self.model, preprocessor=self.p)
return tagger.analyze(words)
@app.route('/predict', methods=['GET'])
def load_and_predict():
load_model()
predict()
However, this leads to a problem whenever multiple requests are the send to the server. How can I make this code thread-safe, or to be more specific, how do I use tensorflow graphs correctly in a multi-threaded environment?