如何在Flask应用程序中设置static_url_path [英] How to set static_url_path in Flask application

查看:100
本文介绍了如何在Flask应用程序中设置static_url_path的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

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

当我尝试:

print app.static_url_path

我得到正确的 static_url_path

但是在我的模板中,当我使用 url_for('static')时,使用jinja2生成的html文件仍然具有默认的静态URL路径/static ,而缺少<我添加的code> PREFIX .

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?

推荐答案

当您创建 Flask()对象时,Flask会创建URL路由.您需要重新添加该路线:

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)

使用正确的静态URL路径配置 Flask()对象会更容易.

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

演示:

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

这篇关于如何在Flask应用程序中设置static_url_path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆