以下面两条路线为例。Flask路线中的尾部斜线
app = Flask(__name__)
@app.route("/somewhere")
def no_trailing_slash():
#case one
@app.route("/someplace/")
def with_trailing_slash():
#case two
根据the docs以下理解:
在情况下,一个,用于路线
"/somewhere/"
的请求将返回404响应。"/somewhere"
有效。万一二,
"/someplace/"
是有效的,"/someplace"
会重定向到"/someplace/"
我想看到的行为是“逆”的情况下,两个行为。例如"/someplace/"
将重定向到"/someplace"
而不是其他方式。有没有办法来定义一个路线来采取这种行为?
从我的理解,strict_slashes=False
可以在路线上设置有效地得到万一有情况下,两个相同的行为,但我希望做的就是重定向行为总是重定向到URL 没有尾部的斜线。
我想过的一种解决方案是使用404错误处理程序,就像这样。 (不知道这是否会甚至工作)
@app.errorhandler(404)
def not_found(e):
if request.path.endswith("/") and request.path[:-1] in all_endpoints:
return redirect(request.path[:-1]), 302
return render_template("404.html"), 404
但我不知道是否有更好的解决方案,就像某种类型的插入式应用配置,类似于strict_slashes=False
,我可以在全局范围。也许一个蓝图或网址规则?
同时实现seperately并有'/ somplace /'重定向到'/ someplace'? – Busturdust
我注意到当你在Flask配置中有'DEBUG = True'时,尾部空格不会被重定向,但当'DEBUG = False'时,它会被重定向。 –
@Busturdust可能可以工作,但会是一种痛苦的管理。我有一些其他想法涉及使用[错误处理程序](http://flask.pocoo.org/docs/0.11/patterns/errorpages/#error-handlers),如果存在无斜杠端点,则返回重定向。也可以使用某种蓝图。但是我已经使用了404错误处理程序来处理其他事情(它可以被烘烤,但我宁愿不),我不确定是否可以通过蓝图实现。理想的解决方案是像全球网址规则一样的投入。 – sytech