More than one static path in local Flask instance More than one static path in local Flask instance flask flask

More than one static path in local Flask instance


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 ;)


You can use a Blueprint with its own static dirhttp://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 wanted to expand on the accepted answer above for anyone who was wondering what app.config['CUSTOM_STATIC_PATH'] was being set to.

In my case I needed a /.well-known dir and so here's what I used:

I placed a new dir in my app root called well-known.
I set a config var like so:

CUSTOM_STATIC_PATH=app.root_path + '/well-known/'

I then used that var as such:

@app.route('/.well-known/<path:filename>')def wellKnownRoute(filename):    return send_from_directory(app.config['CUSTOM_STATIC_PATH'], filename, conditional=True)

Setting conditional=True is smart, this will 404 any requests where the file does not exist.

And of course if you're wondering why you need to set a config value for the dir path, you don't. You can always just use the config's value in place, giving you this instead:

@app.route('/.well-known/<path:filename>')def wellKnownRoute(filename):    return send_from_directory(app.root_path + '/well-known/', filename, conditional=True)

My files for the /.well-known URL path were always going to come from the app root /well-known dir so no point in making it more complicated.

And to note, you would be better off handling this particular case from nginx or whatever server you're using by setting up an additional server block and serving the file from outside the app, I just needed this setup for a dev env for testing.