配置路由
配置路由可以理解为设置url,只需要通过route装饰器,将函数绑定到url上,就可以实现地址的访问
from flask import Flask
app = Flask(__name__)
# 为app.route设置"/index"
# 则可以通过http://localhost:5000/index这个地址进行访问
@app.route("/index")
def index():
return "<h1>index</h1>"
# 为app.route设置"/test"
# 则可以通过http://localhost:5000/test这个地址进行访问
@app.route("/test")
def test():
return "<h1>test</h1>"
注意,在配置路由的过程中,后边添加/或者没有添加/都是可以的
如果你设置的路由为app.route("/index"),那么访问http://localhost:5000/index的时候,会直接请求成功
如果你设置的路由为app.route("/index/"),那么访问http://localhost:5000/index的时候,flask会自动将其重定向到http://localhost:5000/index/
但是最好不要同时添加带/和不带/的两个版本,这样可能导致不确定的行为
为同一响应配置多个路由
比如说,你希望同时将首页配置为/和/index,那么只需要使用多个装饰器,就可以将同一响应解析为多个地址