Flask:网页路由及请求方式的设定

1、Flask路由的实现

  Flask的路由是由route装饰器来实现的

@app.route("/index/")
def index():
    return "hello flask"

注意:

(1)Flask的路由必须以"/"开头,否则将会报错:

if not string.startswith("/"):
    raise ValueError("urls must start with a leading slash")

  上面为Flask中关于路由的源代码,可以看出,如果路由不是以"/"开头,将会抛出"urls must start with a leading slash"异常

(2)一般来说,路由应该与视图函数同名显得比较规范,不可以编写名字相同的视图函数

2、Flask中的路由传参

  在Flask中传参无需使用正则表达式:

@app.route("/index/<name>/<int:age>/")
def index(name, age):
    return "hello {},I'm {} years old".format(name, age)

运行结果:

  常见的参数类型有:str字符串型(默认)、int整型、float浮点型、path路径

注意:

  视图函数中的参数位置可以随意调换,但是进行访问时的路由地址必须按照route装饰器里的路由参数位置进行传参

3、Flask的请求方式设定

  在Flask中,只需要在route装饰器添加并设置methods参数即可完成对视图请求方式的设定

@app.route("/index/<name>/<int:age>/", methods=["GET", "POST"])
def index(name, age):
    return "hello {},I'm {} years old".format(name, age)

查看下面源代码:

if methods is None:
    methods = getattr(view_func, "methods", None) or ("GET",)

  可以看出,methods的值默认为("GET",),即视图函数的默认请求方式为"GET"请求

猜你喜欢

转载自www.cnblogs.com/xmcwm/p/11794459.html