route
装饰器是用于把一个函数绑定到一个 URL 上
from flask import Flask
app = Flask(__name__)
# 如果访问 /,返回 Index Page
@app.route('/')
def index():
return 'Index Page'
# 如果访问 /hello,返回 Hello, World!
@app.route('/hello')
def hello():
return 'Hello, World!'
export FLASK_APP=hello.py
export FLASK_ENV=development
flask run
不仅如此!可以动态地构造 URL 的特定部分,也可以在一个函数上绑定多个不同的规则。
为了给 URL 增加变量的部分,你需要把一些特定的字段标记成<variable_name>
。这些特定的字段将作为参数传入到你的函数中。当然也可以指定一个可选的转换器通过规则<converter:variable_name>
将变量值转换为特定的数据类型。
@app.route('/user/<username>')
def show_user_profile(username):
# 显示用户名
return 'User {}'.format(username)
@app.route('/post/<int:post_id>')
def show_post(post_id):
# 显示提交整型的用户"id"的结果,注意"int"是将输入的字符串形式转换为整型数据
return 'Post {}'.format(post_id)
@app.route('/path/<path:subpath>')
def show_subpath(subpath)