Flask中的路由系統其實我們並不陌生了,從一開始到現在都一直在應用
@app.route("/",methods=["GET","POST"])
為什么要這么用?其中的工作原理我們知道多少?
@app.route() 裝飾器中的參數
methods
methods : 當前 url 地址,允許訪問的請求方式,默認是GET
@app.route('/login', methods=['GET', 'POST']) # methods指定這個列表后,只能有這幾種請求方式,其他的都或被拒絕 def login(): if request.method == "GET": return render_template("login.html") else: session['user'] = request.form.get('username') return redirect("/")
endpoint
endpoint : 反向url地址,默認為視圖函數名 (url_for)
from flask import url_for
# 如果定義一個驗證session的裝飾器,需要應用在多個視圖函數時候,會報錯
@app.route('/', endpoint="this_is_index") # 解決報錯的其中之一方法就是 反向地址 endpoint
# 由於兩個視圖函數都使用同一個裝飾時候,相當於兩個視圖函數重名了,都成了裝飾其中的inner函數,這個時候會報錯
# 錯誤信息類似這種AssertionError: View function mapping is overwriting an existing endpoint function: inner
@wrapper def index():
print(url_for("this_is_index"))
return render_template("index.html")
defaults
defaults : 視圖函數的參數默認值{"nid":100}
from flask import url_for @app.route('/', endpoint="this_is_index", defaults={"nid": 100}) @wrapper def index(nid): print(url_for("this_is_index")) # 打印: / print(nid) # 瀏覽器訪問下"/", 打印結果: 100 return render_template("index.html")
strict_slashes
strict_slashes : url地址結尾符"/"的控制 False : 無論結尾 "/" 是否存在均可以訪問 , True : 結尾必須不能是 "/"
@app.route('/login', methods=['GET', 'POST'], strict_slashes=True) # 加上trict_slashes=True之后 在瀏覽器訪問login后邊加上/就訪問不到了 提示 not fount def login(): if request.method == "GET": return render_template("login.html") else: session['user'] = request.form.get('username') return redirect("/")
redirect_to
redirect_to : url地址重定向
@app.route('/detail', endpoint="this_is_detail", redirect_to="/info") # 此時訪問 就會永久重定向到 /info @wrapper # AssertionError: View function mapping is overwriting an existing endpoint function: inner # 由於使用內部函數想當於把視圖函數名字都修改為了inner 所以報錯 # 解決方法 使用 反向地址 endpoint def detail(): return render_template("detail.html") @app.route('/info') def info(): return "hello world"
subdomain
subdomain : 子域名前綴 subdomian="crm" 這樣寫可以得到 crm.hello.com 前提是app.config["SERVER_NAME"] = "oldboyedu.com"
app.config["SERVER_NAME"] = "hello.com" @app.route("/info",subdomain="crm") def student_info(): return "Hello world" # 訪問地址為: crm.hello.com/info
動態參數路由:
# 使用方法:/<int:nid> /<string:str> /<nid> # 默認字符創
@app.route('/info/<id>') def info(id): print(id) # 瀏覽器url中輸入/info/12 打印結果: 12 return "hello world"
源碼以后解析以后再補