目錄python
methods : 當前 url 地址,容許訪問的請求方式,默認不寫爲GET方法flask
@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}app
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}" # Python3.6的新特性 f"{變量名}"
strict_slashes : url地址結尾符"/"的控制 False : 不管結尾 "/" 是否存在都可以訪問 , True : 結尾必須不能是 "/"dom
# 訪問地址 : /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 : 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"
subdomain : 子域名前綴 subdomian="cnblogs" 這樣寫能夠獲得 cnblogs.aspx.com 前提是app.config["SERVER_NAME"] = "aspx.com"url
app.config["SERVER_NAME"] = "aspx.com" @app.route("/info",subdomain="cnblogs") def student_info(): return "Hello cnblogs info" # 訪問地址爲: cnblogs.aspx.com/info
可是這種動態參數路由,在url_for的時候,必定要將動態參數名+參數值添加進去,不然會拋出參數錯誤的異常blog
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}" # Python3.6的新特性 f"{變量名}"
多個參數傳遞:路由
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}" # Python3.6的新特性 f"{變量名}"