其他分享
首页 > 其他分享> > 3. Flask路由系统

3. Flask路由系统

作者:互联网

一、常用路由系统

- @app.route('/user/<username>')
- @app.route('/post/<int:post_id>')
- @app.route('/post/<float:post_id>')
- @app.route('/post/<path:path>')
- @app.route('/login', methods=['GET', 'POST'])

二、路由参数

1. methods

​ methods:当前url地址,允许访问的请求方式,默认不写为GET方法

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

2. endpoint

​ 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}" 

3. defaults

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

from flask import url_for

@app.route("/info", methods=["GET", "POST"], endpoint="r_info", defaults={"nid": 100})
def student_info(nid):  #这里形参必须有个nid接收
    print(url_for("r_info"))  # /info
    # stu_id = int(request.args["id"])
    print(nid)  # 100
    return f"Hello Old boy {nid}"

4. strict_slashes

​ 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"

5. redirect_to

​ redirect_to:url地址重定向,且为308永久重定向

# 访问地址 : /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"

6. subdomain

​ subdomain : 子域名前缀 subdomian=”cnblogs” 这样写可以得到 cnblogs.aspx.com 前提是app.config[“SERVER_NAME”] = “aspx.com”

app.config["SERVER_NAME"] = "aspx.com"
@app.route("/info",subdomain="cnblogs")
def student_info():
    return "Hello cnblogs info"
# 访问地址为:  cnblogs.aspx.com/info

7. 动态参数路由

​ 就是在url后定义一个参数接收;但是这种动态参数路由,在url_for的时候,一定要将动态参数名+参数值添加进去,否则会抛出参数错误的异常

from flask import url_for

# 访问地址 : http://127.0.0.1:5000/info/1
@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}" 
1. 多个参数传递

from flask import url_for
# 访问地址 : http://127.0.0.1:5000/info/1
@app.route("/info/<nid1>/<nid2>", methods=["GET", "POST"], endpoint="r_info")
def student_info(nid):
    print(url_for("r_info",nid=2,nid=3))  # /info/2/3
    return f"Hello Old boy {nid}" 

标签:info,return,Flask,app,系统,nid,url,route,路由
来源: https://www.cnblogs.com/hq82/p/12636187.html