how to get static files in Flask without url_for('static', file_name='xxx')


Question

I don't want use url_for('static', file_name='foo.jpg') to get static file in template.

how to get static file in this way:

<img src="/pic/foo.jpg" />

thanks

1
10
12/4/2012 3:35:31 PM

Accepted Answer

You can set up your own route to serve static files. Add this method and update the static path directory in the send_from_directory method, then your img tag should work.

@app.route('/pic/<path:filename>')
def send_pic(filename):
    return send_from_directory('/path/to/static/files', filename)

For a production app, you should set up your server to serve static files directly. It would be much faster and use less server resources, but for a few users the difference shouldn't be a problem.

17
11/4/2014 8:01:57 AM

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