Forums

Save matplotlib plot in static folder

Hello,

I want to save a plot in my /static/images folder. But I get an error:

FileNotFoundError: [Errno 2] No such file or directory: '/static/images/output.png'

I tried (nothing works):

fig.savefig("/static/images/output.png")
fig.savefig("static/images/output.png")
fig.savefig("mysite/static/images/output.png")

The only one which works is (but this save the image in my home/username folder ):

 fig.savefig("output.png")

What do I wrong?

BR Marco

You cannot save anything into /static - it doesn't exist. If you want to serve a static file, create a directory that you want to serve it from, create a static files mapping in your web app (see https://help.pythonanywhere.com/pages/StaticFiles/ and https://help.pythonanywhere.com/pages/DebuggingStaticFiles/) and save the plot to that directory.

Thank you. Now I understand everything :D But I have now a little problem with draw the picture with html. I though it should work like this:

return '''
<!DOCTYPE html>
<html>
    <head>
        <title>Index</title>
    </head>
    <body>
        <img src="/static/images/output.png" alt="User Image">
    </body>
</html>
'''

That should be fine as long as the file you're trying to get is being served from that location.

The file is there but the picture is not shown

I see that you have a static file mapping set up from /static/ to /home/M4cM4rco/mysite. That means that the URL /static/images/output.png will map to the file /home/M4cM4rco/mysite/images/output.png. Is the file at that location? A mapping like that would be unusual, because it means that any file inside mysite can be accessed by someone who knows the file's location; you would normally map /static/ to something like /home/M4cM4rco/mysite/static.

That was the plan... the picture which will be saved should be accessed by everyone. The background: I use the WebApp with the api 'twilio' (api for sending sms or whatsapp messages). When I send a message to the twilio WhatsApp Bot, the output.png should deleted and generated new --> works perfectly But then twilio should send me the output.png and for that he need the URL and this do not work

If you make the change that I suggested in my last post, does it fix the problem?