添加路由
我们熟知添加路由的方式是装饰器:
@app.route('/') def hello_world(): return 'Hello World!'
#访问web得到
'Hello World!'
其实还可以这样:
def hello_world(): return 'Hello World!' app.add_url_rule('/',view_func=hello_world) #感兴趣可展开route源码查看
路由中的变量
路由中可以自定义一些参数,参数就涉及到类型:
int:接受整数
float:同 int ,但是接受浮点数
path:和默认的相似,但也接受斜线
@app.route('/test/<test>') def route_test(test): return 'test:%s' % test #路径变量
#访问web(127.0.0.1:5000/test/1234)得到
test:1234
@app.route('/int-test/<int:test>') def route_test1(test): return 'int test:%s' % test #自定义变量类型
此时访问web(127.0.0.1:5000/int-test/ss)得到404 Not Found,必须使用数字才能得到返回
利用函数名字获取路由路径url_for
from flask import Flask,url_for @app.route('/gg') def hello_world(): print(url_for('hello_world')) return 'Hello World!' #out:/gg