flask之route中的參數

flask的路由中有一些參數html

使用案例

from flask import Flask, render_template, url_for, session, request, redirect

app = Flask(__name__)
app.secret_key = "wang"


def confirm(func):
    def inner(*args, **kwargs):
        if session.get('auth'):
            return func(*args, **kwargs)
        else:
            next_url = request.path[1:]
            return redirect(url_for("login") + f"?next={next_url}")

    return inner


@app.route('/', endpoint="index", redirect_to="/shopping")
@confirm
def index():
    return "index"


@app.route('/login/', methods=["GET", "POST"], defaults={"nid": 1001, }, strict_slashes=True)
def login(nid):
    msg = ""
    print("===>", url_for("index"))
    # ===> /login, 當沒有定義endpoint是, 能夠直接寫函數名, 當定義了
    print("===>", nid)
    # ===> 1001
    if request.method == "POST":
        auth = request.form.get("auth")
        if auth:
            session["auth"] = auth
            next_url = request.args.get("next", "index")
            return redirect(url_for(next_url))
        else:
            msg = "error"
    return render_template("login.html", msg=msg)


@app.route('/shopping/<int:year>/<string:month>', endpoint="shopping")
def shopping(year, month):
    print(year, type(year), month, type(month))
    # 1 <class 'int'> 2 <class 'str'>
    return "Shopping"


if __name__ == '__main__':
    app.run(debug=True)

參數解析

重要的

endpoint=""     默認是函數名, 能夠在app.route()的關鍵字參數中定義
url_for("")     反向地址, 經過視圖函數名, 或endpoint解析對應的URL
methods=[]      該視圖函數能處理的請求方式, 默認是GET, 當從新定義了methods, 那麼默認的GET也會被覆蓋

 

通常的

defaults={}     給視圖函數傳遞參數, 能夠做爲默認參數, 傳了就必須的接
strict_slashes=Bool     嚴格的使用"/", URL中沒有"/", 訪問時也不能有, URL中有"/", 你訪問時沒有, 會經過301進行永久重定向
redirect_to=""      永久重定向

 

動態路由參數

'/shopping/<int:year>/<string:month>'   路由中使用參數, 並能夠轉換參數的數據類型, 切記數字能夠轉字符串, 字符串不能轉數字
相關文章
相關標籤/搜索