flask中路由系統
阿新 • • 發佈:2019-01-09
flask中的路由我們並不陌生,從一開始到現在都一直在應用
@app.route("/",methods=["GET","POST"])
[email protected]()裝飾器中的引數
methods:當前url地址,允許訪問的請求方式
@app.route("/info", methods=["GET", "POST"]) def student_info(): stu_id = int(request.args["id"]) return f"Hello World! {{ 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 stu {stu_id}" # Python3.6的新特性 f"{變數名}"
defaults : 檢視函式的引數預設值{"nid":1}
from flask importurl_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 stu {nid}" # Python3.6的新特性 f"{變數名}"
strict_slashes : url地址結尾符"/"的控制 False : 無論結尾 "/" 是否存在均可以訪問 , True : 結尾必須不能是 "/"
# 訪問地址 : /info @app.route("/info", strict_slashes=True) def student_info(): return "Hello stu info" # 訪問地址 : /infos or /infos/ @app.route("/infos", strict_slashes=False) def student_infos(): return "Hello stu infos"
redirect_to : url地址重定向
# 訪問地址 : /info 瀏覽器跳轉至 /infos @app.route("/info", strict_slashes=True, redirect_to="/infos") def student_info(): return "Hello stu info" @app.route("/infos", strict_slashes=False) def student_infos(): return "Hello stu infos"
subdomain : 子域名字首 subdomian="mikers.cn" 這樣寫可以得到 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 stu info" # 訪問地址為: DragonFire.oldboy.com/info
2.動態引數路由
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 stu {nid}" # Python3.6的新特性 f"{變數名}"
<int:nid> 就是在url後定義一個引數接收
但是這種動態引數路由,在url_for的時候,一定要將動態引數名+引數值新增進去,否則會丟擲引數錯誤的異常