【问题标题】:Why doesn't rendering a template work when there's a trailing slash in app.route?当 app.route 中有斜杠时,为什么渲染模板不起作用?
【发布时间】:2016-02-09 22:40:23
【问题描述】:

我正在使用 Flask 应用程序并且遇到了一些路由问题。

以下函数可以正常工作(如预期的那样呈现模板):

@app.route('/page1', methods = ['POST'])
def page1():
    ...
    return render_template('page1.html')

然而,几乎相同的功能

@app.route('/page1/', methods = ['POST'])
def page1():
    ...
    return render_template('page1.html')

不再能够加载与page1.html 关联的任何 css 资源。 html 加载顺利,只是找不到其他资源。

如果有人对为什么额外的尾部斜杠会导致这种情况有所了解,那就太好了!

【问题讨论】:

  • 请分享模板。

标签: url flask routes


【解决方案1】:

这是默认的烧瓶行为,see werkzeug docs。要更改它,请使用:

@app.route('/page1', strict_slashes=False)

或者要普遍改变它,改变应用行为:

app = Flask(__name__)    
app.url_map.strict_slashes = False

另一种方法是将@app.route 包装为:

def route(*a, **kw):
    kw['strict_slashes'] = kw.get('strict_slashes', False)
    return app.route(*a, **kw)

并使用@route 作为路由装饰器,路由带有或不带有斜线(而不是@app.route)。

首选最后一种方式,因为它仅适用于您想要此行为的路由,而不是单个路由或所有路由。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-23
    • 2011-06-21
    • 2017-03-22
    • 2023-02-08
    • 2013-07-10
    • 1970-01-01
    • 2012-03-25
    相关资源
    最近更新 更多