Search code examples
pythonflaskjinja2static-files

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


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


Solution

  • 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.