Flask学习笔记 —— 路由
路由
现代 web 应用都使用有意义的 URL ,这样有助于用户记忆,网页会更得到用户的青睐, 提高回头率。
使用 route() 装饰器来把函数绑定到 URL:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Index Page'
@app.route('/poetea')
def poetea():
return 'Hello, I am Poetea'
但是能做的不仅仅是这些!你可以动态变化 URL 的某些部分, 还可以为一个函数指定多个规则。
变量规则
通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 <converter:variable_name> ,可以 选择性的加上一个转换器,为变量指定规则。
@app.route('/user/<username>')
def show_user(username):
return 'User: %s' % escape(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return 'Subpath %s' % escape(subpath)
注:上述代码需要 pip install regex(https://pypi.org/project/regex/),然后加入一行
from regex import escape
才能使用 escape。
转换器类型:
- string:(缺省值) 接受任何不包含斜杠的文本
- int:接受正整数
- float:接受正浮点数
- path:类似 string ,但可以包含斜杠
- uuid:接受 UUID 字符串
浙公网安备 33010602011771号