app.route
路由传参的5中方法
@app.route('/user/') # 没有参数
@app.route('/user/<username>') # 字符串参数
@app.route('/post/<int:post_id>') # 整形参数
@app.route('/post/<float:post_id>') # 浮点参数
@app.route('/post/<path:path>') # 路径参数
例子
@app.route('/')
def index():
pass
@app.route('/<username>')
def show_user(username):
pass
@app.route('/post/<int:post_id>')
def show_post(post_id):
pass
一个函数同时定义多个规则
@app.route('/users/', defaults={'page': 1})
@app.route('/users/page/<int:page>')
def show_users(page):
pass
app.add_url_rule
@app.route
和app.add_url_rule
参数
add_url_rule(rule, endpoint=None, view_func=None, provide_automatic_options=None, **options)
class werkzeug.routing.Rule(string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, redirect_to=None, alias=False, host=None)
参数 | 描述 |
---|---|
rule | URL规则 |
view_func | 函数名称,修饰符不用添加 |
defaults | URL中的默认参数defaults={'k':'v'} |
endpoint=None | the endpoint for the registered URL rule,itself assumes the name of the view function as. Flask,反向生成URLurl_for('名称') ,否则url_for() 默认使用函数名称 |
methods=None | 请求方法method=["GET","POST"] ,默认为get,不添加则不能使用 |
strict_slashes=None | 对URL最后的 / 符号是否严格要求 |
redirect_to=None | 重定向到指定地址 |
subdomain=None | 子域名访问 |
@app.route('/')
def index():
pass
# 等价于
def index():
pass
app.add_url_rule('index', '/')
app.view_functions['index'] = index
methods
methods=['GET', 'POST']
如果不声明methods,则此页面只能接收get请求,拒绝post请求。
参考文献:
http://flask.pocoo.org/docs/0.12/api/#url-route-registrations
https://www.cnblogs.com/wupeiqi/articles/7552008.html