路由定义以及变量的规则
一、 路由
1.查看路由装饰器的源码
@app.route('/index')
def index():
return ''
URL : http://192.168.1.10:8080/index
route:
def route(self, rule, **options):
def decorator(f):
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
使用 route() 装饰器来把函数绑定到 URL,这个装饰器其实就是将rule字符串跟视图函数通过add_url_rule()实现的绑定。
@app.route('/index')
def index():
return 'welcome everyone!'
等效的
def index():
return 'welcome everyone!'
app.add_url_rule('/index', view_func=index)
2.路由的常用参数
(1)通常第一个参数表示的是访问的路径,比如/user,/login,/lgout等
(2)另外默认什么都不加的时候,表示的采用get进行访问。
Web 应用使用不同的 HTTP 方法处理 URL , 缺省情况下,一个路由发送 GET 请求。 可以使用 route() 装饰器的 methods 参数来处理不同的 HTTP 方法:
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
如果当前使用了 GET 方法, Flask 会自动添加 HEAD 方法支持,并且同时还会按照 HTTP RFC 来处理 HEAD 请求。同样, OPTIONS 也会自动实现。
查看路由规则表:app.url_map
二、路由的变量规则
类型 | 说明 |
---|---|
string | (缺省值) 接受任何不包含斜杠的文本 * |
int | 接受正整数 * |
float | 接受正浮点数 |
path | 类似 string ,但可以包含斜杠 |
uuid | 接受 UUID 字符串 |
带*表示的是常用的变量方式
@app.route('/getcity/<key>') # key就是一个变量名,默认是字符串类型的
def get_city(key): # 参数是必须添加的
print(type(key))
return data.get(key)
三、唯一的 URL / 重定向行为
以下两条规则的不同之处在于是否使用尾部的斜杠:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
(1)projects 的 URL 尾部有一个斜杠,看起来就如同一个文件夹。 如果访问的时候没有带上/,Flask 会自动进行重定向,帮你在尾部加上一个斜杠。
(2)about 的 URL 没有尾部斜杠,因此其行为类似于访问一个文件。如果访问这个 URL 时添加了尾部斜杠就会得到一个 404 错误。这样可以保持 URL 唯一,并帮助 搜索引擎避免重复索引同一页面。