本文介绍了在Flask路径规则中跟踪斜线触发器404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 / users 下的任何路径重定向到一个静态的应用程序。下面的视图应该捕获这些路径并提供适当的文件(它只是打印这个例子的路径)。这适用于 / users / users / 604511 / users / 604511 / action 。为什么路径 / users / 导致404错误?

  bp.route('/ users')
@ bp.route('/ users /< path:path>')
def serve_client_app(path = None):
return path


解决方案

您的 / users route缺少一个结尾的斜线,Werkzeug将其解释为不符合尾部斜线的显式规则。或者添加尾部斜线,如果URL没有,Werkzeug会重定向,或者设置,并且Werkzeug将匹配规则,不论是否使用斜线。

  @ app.route('/ users /')
@ app.route('/ users /< path:path>')
def users(path = None) :
return str(path)
$ bc = app.test_client()
print(c.get('/ users'))#302 MOVED PERMANENTLY(to / users /)
print(c.get('/ users /'))#200 OK
print(c.get('/ users / test'))#200 OK





  @ app.route('/ users',strict_slashes = False )
@ app.route('/ users /< path:path>')
def users(path = None):
return str(path)

c = app.test_client()
print(c.get('/ users'))#200 OK
print(c.get('/ users /'))#200 OK
print(c.get('/ users / test'))#200 OK


I want to redirect any path under /users to a static app. The following view should capture these paths and serve the appropriate file (it just prints the path for this example). This works for /users, /users/604511, and /users/604511/action. Why does the path /users/ cause a 404 error?

@bp.route('/users')
@bp.route('/users/<path:path>')
def serve_client_app(path=None):
    return path
解决方案

Your /users route is missing a trailing slash, which Werkzeug interprets as an explicit rule to not match a trailing slash. Either add the trailing slash, and Werkzeug will redirect if the url doesn't have it, or set strict_slashes=False on the route and Werkzeug will match the rule with or without the slash.

@app.route('/users/')
@app.route('/users/<path:path>')
def users(path=None):
    return str(path)

c = app.test_client()
print(c.get('/users'))  # 302 MOVED PERMANENTLY (to /users/)
print(c.get('/users/'))  # 200 OK
print(c.get('/users/test'))  # 200 OK
@app.route('/users', strict_slashes=False)
@app.route('/users/<path:path>')
def users(path=None):
    return str(path)

c = app.test_client()
print(c.get('/users'))  # 200 OK
print(c.get('/users/'))  # 200 OK
print(c.get('/users/test'))  # 200 OK

这篇关于在Flask路径规则中跟踪斜线触发器404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 01:54