Search code examples
flask

How to set static_url_path in Flask application


I want to do something like this:

app = Flask(__name__)
app.config.from_object(mypackage.config)
app.static_url_path = app.config['PREFIX']+"/static"

when I try:

print app.static_url_path

I get the correct static_url_path

But in my templates when I use url_for('static'), The html file generated using jinja2 still has the default static URL path /static with the missing PREFIX that I added.

If I hardcode the path like this:

app = Flask(__name__, static_url_path='PREFIX/static')

It works fine. What am I doing wrong?


Solution

  • Flask creates the URL route when you create the Flask() object. You'll need to re-add that route:

    # remove old static map
    url_map = app.url_map
    try:
        for rule in url_map.iter_rules('static'):
            url_map._rules.remove(rule)
    except ValueError:
        # no static view was created yet
        pass
    
    # register new; the same view function is used
    app.add_url_rule(
        app.static_url_path + '/<path:filename>',
        endpoint='static', view_func=app.send_static_file)
    

    It'll be easier just to configure your Flask() object with the correct static URL path.

    Demo:

    >>> from flask import Flask
    >>> app = Flask(__name__)
    >>> app.url_map
    Map([<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])
    >>> app.static_url_path = '/PREFIX/static'
    >>> url_map = app.url_map
    >>> for rule in url_map.iter_rules('static'):
    ...     url_map._rules.remove(rule)
    ... 
    >>> app.add_url_rule(
    ...     app.static_url_path + '/<path:filename>',
    ...     endpoint='static', view_func=app.send_static_file)
    >>> app.url_map
    Map([<Rule '/PREFIX/static/<filename>' (HEAD, OPTIONS, GET) -> static>])