More than one static path in local Flask instance

You can use a Blueprint with its own static dir http://flask.pocoo.org/docs/blueprints/

Blueprint

blueprint = Blueprint('site', __name__, static_url_path='/static/site', static_folder='path/to/files')
app.register_blueprint(blueprint)

Template

{{ url_for('site.static', filename='filename') }}

I have been using following approach:

# Custom static data
@app.route('/cdn/<path:filename>')
def custom_static(filename):
    return send_from_directory(app.config['CUSTOM_STATIC_PATH'], filename)

The CUSTOM_STATIC_PATH variable is defined in my configuration.

And in templates:

{{ url_for('custom_static', filename='foo') }}

Caveat emptor - I'm not really sure whether it's secure ;)


If i have images stored in images dir like following

images/
  dir1/
    image1.jpg
  dir2/
    image2.jpg

then we can access these images with following url: http://localhost:5000/images/dir1/image1.jpg with the help of below code

from flask import Flask, send_from_directory


app = Flask(__name__, static_folder='main_static_dir')


@app.route('/images/<path:filename>')
def base_static(filename):
    return send_from_directory(app.root_path + '/images/', filename)


if __name__ == '__main__':
    app.run(debug=True)

Tags:

Python

Html

Flask