Flask - 路由系统

Flask - 路由系统

最简单用法:浏览器

@app.route("/",methods=["GET","POST"])

下面介绍可是还有其余参数和用法app

@app.route()装饰器中的经常使用参数

methods : 当前 url 地址,容许访问的请求方式

@app.route("/info", methods=["GET", "POST"])
def student_info():
    stu_id = int(request.args["id"])
    return f"Hello Old boy {stu_id}"  # Python3.6的新特性 f"{变量名}"

endpoint:反向url地址,默认为视图函数名(url_for)

from flask import url_for


@app.route("/info", methods=["GET", "POST"], endpoint="r_info")
def student_info():
    print(url_for("r_info"))  # /info
    stu_id = int(request.args["id"])
    return f"Hello Old boy {stu_id}"  # Python3.6的新特性 f"{变量名}"

defaults:视图函数的参数默认值{"nid":1}

from flask import url_for


@app.route("/info", methods=["GET", "POST"], endpoint="r_info", defaults={"nid": 100})
def student_info(nid):
    print(url_for("r_info"))  # /info
    # stu_id = int(request.args["id"])
    print(nid)  # 100
    return f"Hello Old boy {nid}"  # Python3.6的新特性 f"{变量名}"

strict_slashes : url地址结尾符"/"的控制 False : 不管结尾 "/" 是否存在都可以访问 , True : 结尾必须不能是 "/"

# 访问地址 : /info 
@app.route("/info", strict_slashes=True)
def student_info():
    return "Hello Old boy info"


# 访问地址 : /infos  or  /infos/
@app.route("/infos", strict_slashes=False)
def student_infos():
    return "Hello Old boy infos"

redirect_to : 301永久重定向 在进入视图函数以前进行跳转

# 访问地址 : /info 浏览器跳转至 /infos
@app.route("/info", strict_slashes=True, redirect_to="/infos")
def student_info():
    return "Hello Old boy info"

@app.route("/infos", strict_slashes=False)
def student_infos():
    return "Hello Old boy infos"

subdomain : 子域名前缀 subdomian="DragonFire" 这样写能够获得 DragonFire.oldboyedu.com 前提是app.config["SERVER_NAME"] = "oldboyedu.com"

app.config["SERVER_NAME"] = "oldboy.com"

@app.route("/info",subdomain="DragonFire")
def student_info():
    return "Hello Old boy info"

# 访问地址为:  DragonFire.oldboy.com/info

动态参数路由

@app.route("/info/<int:nid>", methods=["GET", "POST"], endpoint="r_info")
def student_info(nid):
    print(url_for("r_info",nid=2))  # /info/2
    return f"Hello Old boy {nid}"  # Python3.6的新特性 f"{变量名}"

就是在url后定义一个参数接收 dom

可是这种动态参数路由,在url_for的时候,必定要将动态参数名+参数值添加进去,不然会抛出参数错误的异常函数

若是正则玩的好, 还能够用正则匹配url

相关文章
相关标签/搜索