@app.route('/index')
@app.route('/')
def index():
return 'index'
# 打印路由表
print(app.url_map)
>console
Map([<Rule '/index' (OPTIONS, GET, HEAD) -> index>,
<Rule '/' (OPTIONS, GET, HEAD) -> index>,
<Rule '/static/' (OPTIONS, GET, HEAD) -> static>])
@decorater # 无效
@app.route('/')
@decorater # 有效
def index():
# if name:
# return name
return 'no name'
def decorater(func):
def wrapper(*args, **kwargs):
import time
print(time.time())
return func(*args, **kwargs) # 视图函数装饰器仅能返回视图函数功能
return wrapper
/*/
与/*
的区别
- @app.route(’/index/’), 使用/index路径访问时,重定向到/index/,使用/index/正常访问
- @app.route(’/index’), 使用/index路径访问时,正常访问,使用/index/访问报错404
from flask import Flask
app = Flask(__name__)
def count(f):
app.config['num'] = 0
def wrapper(*args, **kwargs):
app.config['num'] += 1
print(app.config['num'])
return f(*args, **kwargs)
return wrapper
@app.route('/')
@count
def index():
return 'index'
if __name__ == '__main__':
app.run(debug=True)
@app.route('/house/' )
def house_detail(content):
return '您请求的房源信息是:%s' % content
* 参数需要放在两个尖括号中间 <>
* 视图函数中需要放和url中参数同名的参数
- str(默认), 不能包含‘/’
- int
- float
- path,可以包含‘/’
- uuid
# int 参数
@app.route('/house/' )
def house_detail(house_id):
return '您请求的房源编号是:%d' % house_id
# path 参数
@app.route('/getpath//' )
def hello_path(url_path):
return 'path: %s' % url_path
# uuid 参数
@app.route('/getuuid/')
def get_uuid():
a = uuid.uuid4()
return str(a)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
@app.route('/index', redirect_to='hello')
def index():
return 'index'
@app.route('/hello')
def hello():
return 'hello'
https://www.jianshu.com/p/0611f044efc4
@app.route('/hello/', defaults={
'id': None})
@app.route('/hello/' )
def hello(id):
return f'hello {id}'
@app.route('/hello/')
@app.route('/hello/' )
def hello(id=None):
return f'hello {id}'