Flask路由规则中反斜杠的使用

2019-06-13  本文已影响0人  dnsir

使用Flask时会设计一些路由规则,有些URL里带反斜杠 /,有些没有带反斜杠/,对于URL来说,有没有反斜杠有什么区别呢?
示例代码:

from flask import Flask

app = Flask(__name__)

@app.route('/test/')
def test_page_with_slash():
    return '/test/'

@app.route('/test')
def test_page_no_slash():
    return '/test'

if __name__ == '__main__':
    app.run()

访问结果:

  1. 访问/test/ 返回结果是/test/
  2. 访问/test 返回结果也是/test/
    似乎路由规则/test没有任何作用,通过观察网络请求,访问/test时,Flask会返回301重定向到/test/,所以返回结果也是/test/

根据参考资料:

  1. https://stackoverflow.com/questions/21050320/flask-301-response
  2. https://werkzeug.palletsprojects.com/en/0.15.x/routing/#werkzeug.routing.Rule
    以及werkzeug官方文档:

URL rules that end with a slash are branch URLs, others are leaves. If you have strict_slashes enabled (which is the default), all branch URLs that are matched without a trailing slash will trigger a redirect to the same URL with the missing slash appended. 引用自 https://werkzeug.palletsprojects.com/en/0.15.x/routing/#werkzeug.routing.Rule

翻译:

URL规范中以/结尾称之为分支URL, 其余称之为叶子URL. 如果开启strict_slashed(默认是打开的),如果未以/结尾的URL请求匹配上分支URL(匹配是不算URL),那么Flask将该URL请求将会重定向到分支URL.

在Flask的文档中http://flask.pocoo.org/docs/1.0/quickstart/#routing
提到:

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

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

对于/projects/,如果访问/projects,Flask将会重定向到/projects/,
对于/about,如果访问/about/,将会出现404
这种规则可以使即使用户访问不输入/服务器也能正常工作,并且URL的唯一性,也避免搜索引擎索引同一个页面两次.
如果不允许这种规则可以设置strict_slashes=False

特别需要注意的是,这种规则还跟路由规则代码顺序有关系

# 先声明/test路由规则
@app.route('/test')  
def test_page_no_slash():
    print('test_page_no_slash')
    return '/test'

@app.route('/test/')
def test_page_with_slash():
    print('test_page_with_slash')
    return '/test/'

此时访问/test 返回/test,访问/test/ 返回 /test/,理解起来就是匹配规则根据代码的声明顺序进行比较

@app.route('/test/')
def test_page_with_slash():
    print('test_page_with_slash')
    return '/test/'

@app.route('/test')
def test_page_no_slash():
    print('test_page_no_slash')
    return '/test'

像这种写法就肯定,默认无论访问/test/test/都会返回/test/,因为规则是这样的定义的,其实就是第二个路由规则其实没有任何作用。

那么有没有可能改变这种规则呢?根据文档,如果strict_slashes = False,那么就会忽略反斜杠

@app.route('/test/', strict_slashes=False)
def test_page_with_slash():
    print('test_page_with_slash')
    return '/test/'

@app.route('/test')
def test_page_no_slash():
    print('test_page_no_slash')
    return '/test'

无论访问/test/还是/test都会返回 /test/. strict_slashes=False,表示忽略反斜杠.

同理可以访问

@app.route('/test', strict_slashes=False)
def test_page_no_slash():
    print('test_page_no_slash')
    return '/test'

@app.route('/test/', strict_slashes=False)
def test_page_with_slash():
    print('test_page_with_slash')
    return '/test/'

无论访问/test/还是/test都会返回/test, 这里也发现第二个规则其实就没有用了.

上一篇 下一篇

猜你喜欢

热点阅读