关于python:Flask路线和斜线

Flask route and slashes

在烧瓶路线上我有个问题

我的路线是

1
2
3
@app.route('/user/<string:user>/')
def user(user):
    return '' + str(user)

当我访问localhost:5000/user/ahmed/并在URL末尾加斜线时,一切都正常。

但是如果我访问localhost:5000/user/ahmed而没有最后一个斜杠

flask将我重定向到localhost:5000/user/ahmed/none并给我404


以下是直接从烧瓶文档中获取的一些相关信息

Unique URLs / Redirection Behavior

Flask’s URL rules are based on Werkzeug’s routing module. The idea
behind that module is to ensure beautiful and unique URLs based on
precedents laid down by Apache and earlier HTTP servers.

Take these two rules:

1
2
3
4
5
6
7
@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    return 'The about page'

Though they look rather similar, they differ in their use of the trailing
slash in the URL definition. In
the first case, the canonical URL for the projects endpoint has a
trailing slash. In that sense, it is similar to a folder on a
filesystem. Accessing it without a trailing slash will cause Flask to
redirect to the canonical URL with the trailing slash.

In the second case, however, the URL is defined without a trailing
slash, rather like the pathname of a file on UNIX-like systems.
Accessing the URL with a trailing slash will produce a 404"Not Found"
error.

This behavior allows relative URLs to continue working even if the
trailing slash is omitted, consistent with how Apache and other
servers work. Also, the URLs will stay unique, which helps search
engines avoid indexing the same page twice.