import os
from flask import Flask, escape, url_for, redirect, send_file
app = Flask(__name__)
@app.route('/')
def index():
return 'index'
@app.route('/login', redirect_to='/new_login') # 不经过视图函数,直接永久重定向到新路由
def login():
return 'login'
@app.route('/see/<str:args>') # 动态路由参数
def see(args):
return f'当前是第{args}页'
@app.route('/look/<args>') # 动态路由参数利用send_file 限定访问目录和返回文件
def look(args):
return send_file(os.path.join('upload', args))
@app.route('/user/<username>')
def profile(username):
return '{}\'s profile'.format(escape(username))
# url_for() 函数用于构建指定函数的 URL。
# 它把函数名称作为第一个 参数。
# 它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量 将添加到 URL 中作为查询参数。
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
# 输出结果
# /
# /login
# /login?next=/
# /user/John%20Doe
if __name__ == '__main__':
app.run()