Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: How to get url for dynamically generated image file?

Tags:

python

flask

from flask import Flask, redirect, url_for

app = Flask(__name__)
@app.route('/')
def index():
        generate_img("test.jpg");
        return '<img src=' + url_for(filename='test.jpg') + '>'

generate_img() will output a random image to the current directory (same folder as this script).

I am getting 404, I navigate to mydomain.com/test.jpg but it's not there.

like image 270
KJW Avatar asked Aug 20 '12 09:08

KJW


2 Answers

Reason of a 404 error is that there is no such view to handle this. To serve images from flask, save the image inside static folder and then you can access image at this url

mydomain.com/static/test.jpg

     from flask import Flask, redirect, url_for

     app = Flask(__name__)
     @app.route('/')
     def index():
          generate_img("test.jpg"); #save inside static folder
          return '<img src=' + url_for('static',filename='test.jpg') + '>' 

Static folder is there to serve all the media, be it css, javascript,video or image files with everything accessible at mydomai.com/static/filename. Remember you should not use flask serving from static folder in production. This feature is only for development.

like image 180
codecool Avatar answered Nov 14 '22 01:11

codecool


Assuming the image is actually generated (that is, that index() is called), the reason for the 404 is that there is no route that points to the image, so Flask will tell you there is no mydomain.com/test.jpg. A static webserver like Apache or Nginx will by default map paths from a root to URLs, but an ordinary Flask/Werkzeug/WSGI setup will not do that.

Perhaps you want to create a resource that directly returns the image instead?

EDIT: Something similar should be able to serve images.

@app.route("/imgs/<path:path>")
def images(path):
    generate_img(path)
    fullpath = "./imgs/" + path
    resp = flask.make_response(open(fullpath).read())
    resp.content_type = "image/jpeg"
    return resp

EDIT2: Of course, generate_img could probably be rewritten so it never write to disk but instead return image data directly.

like image 26
Bittrance Avatar answered Nov 14 '22 01:11

Bittrance