Domingo Domingo - 13 days ago 6
Python Question

How to read and write files with Flask with Ubuntu and apache server

I am trying to deploy an app that writes and reads png images with Flask. Locally I can run my script with no errors, except when I run it on my server.

I deployed using this guide on DigitalOcean. It uses apache, wsgi and virtualenv.

This an example of my code:

from flask import Flask
from flask import send_file
from PIL import Image

app = Flask(__name__)

@app.route("/")
def hello():
img = Image.new('RGB', (200, 100), (255, 255, 255))
img.save('output.png')
return send_file('output.png', mimetype='image/png')

if __name__ == "__main__":
app.run()


I found out that what is causing the problem is
img.save('output.png')
I found also that if I try to load a font like:
font = ImageFont.truetype("Archive.otf", 60)
it doesn't work neither. My .png and .otf files are in the same folder as
__init__.py


I guess I am messing up with the configuration or the directrory paths of apache. If I run
img.save
outside the flask enviroment it works, so it is not a problem with libraries or dependencies.

Answer

You need to use an absolute path, like /var/www/somedir/somefile. This is because Flask under Apache does not give Python a usable working directory. I would suggest making the path configurable.