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


Question

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.

1
4
8/20/2012 9:11:19 AM

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.

6
8/20/2012 12:48:17 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon