24

I'm using flask, matplotlib to save image and tensorflow to create a session. I'm getting the above error when I run the following code. Does the flask route run on a separate thread? How can I make fig.saveFig piece of code run on the Main thread. Thanks a lot

 @app.route('/open', methods = ['GET', 'POST'])
 def sendOutput():
     global loss,a2,xP,yP,scale,sess,fig
     test_X,test_Y = own_model.getEvaluateData(scale)
     cost,ans = sess.run([loss,a2],feed_dict={xP:test_X,yP:test_Y})
     d = np.array(ans) - np.array(test_Y)
     val = hist(d,100)
     sess.close()
     fig.saveFig('abc.png') //Errror on this line

3 Answers 3

86

I was on the same situation, Flask with Matplotlib combo. What worked for me is to specify Agg as Matplotlib backend.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

# Your code here

You can refer to Matplotlib documentation (Matplotlib in a web application server) for the details.

3
  • 13
    Note you need to put this code before any other imports, which might be already importing matplotlib or setting the Tkinter backend. Jul 5, 2018 at 17:08
  • 9
    This works like a charm, Btw what does Agg actually do? Nov 22, 2019 at 9:20
  • 2
    Hey, thanks for the answer. My code works now but I still get a Warning UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail. Do you know about anything I could do to not get this warning?
    – Riptide
    Nov 2, 2020 at 10:07
3

apparently this is an issue with TKinter. You don't have your full error message posted (you really should do that), but I'm working on something very similar so I'm 99.9% sure your problem is the same as mine. I'm building an app with tensorflow, flask, blah blah. I get the same error, intermittently (sometimes it works). Here are some links to similar questions. I hope this helps! I think my solution will be moving away from matplotlib.

0

Threading issues. I had the same issue when working with lime. Here is what fixed it for me.

I changed from:

if __name__=="__main__":
    app.run(host="0.0.0.0", port=5000)

To:

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 5000, app)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.