flask 重定向到上一個頁面,referrer、next參數 --


重定向會上一個頁面

在某些場景下,我們需要在用戶訪問某個url后重定向會上一個頁面,比如用戶點擊某個需要登錄才能訪問的連接,這時程序會重定向到登錄頁面,當用戶登錄后比較合理的行為是重定向到用戶登錄前瀏覽的頁面。

 

下面的例中,在foo和bar視圖中生成連接,鏈接過去后,沒有重定向會上一個頁面


@app.route('/foo')
def foo():
    return '<h1>Foo page </h1><a href="%s">Do something</a>' %url_for('do_something')

@app.route('/bar')
def bar():
    return '<h1>Bar page</h1><a href="%s">Do something </a>' % url_for('do_something')

@app.route('/do_something')
def do_something():
    return redirect(url_for('hello'))

@app.route('/hello')
def hello():
    name = request.args.get('name')
    if name is None:
        name = request.cookies.get('name','xiaxiaoxu')#從cookie中獲取name值
       
response = '<h1>Hello, %s</h1>' % name
    return response

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

 

結果:

 

訪問127.0.0.1:5000/foo或者127.0.0.1:5000/bar后,頁面出現連接,點擊鏈接后,進入hello頁面,之后停留在了hello頁面

 

點擊鏈接后重定向到了hello頁面

 

我們的目的是在鏈接后,返回原來的頁面

 

重定向會上一個頁面,關鍵是獲取上一個頁面的URL。

獲取上一個頁面的URL有兩種方法:

HTTP referrer

HTTP referrer是一個用來記錄請求發源地址的HTTP首部字段(HTTP_REFERER),即訪問來源。當用戶在某個站點點擊鏈接,瀏覽器想新鏈接所在的服務器發起請求,請求的數據中包含的HTTP_REFERER字段記錄了用戶所在的原站點URL。

 

在flask中,referer的值可以通過請求對象的referrer屬性獲取,即request.referrer

 

 

修改do_something視圖函數:

@app.route('/do_something')
def do_something():
    return redirect(request.referrer)

 

在bar頁面上再次點擊鏈接

 

有的時候,referrer字段可能是空值,比如用戶直接在瀏覽器地址欄輸入URL或者因為防火牆或者瀏覽器設置自動清除或修改referer字段,我們需要添加一個備選項:

return redirect(request.referrer or url_for('hello'))

 

 

查詢參數next

除了自動從referrer獲取,另一種更常見的方式是在URL中手動加入包含當前頁面URL的查詢參數,這個查詢參數一般命名為next

在bar視圖中的鏈接do_something對應的視圖添加next參數(在/do_someghing后加參數)

 

 

def bar():
    #print dir(request)
   
print "request.full_path:",request.full_path
    #print "request.url:",request.url
   
return '<h1>Bar page</h1><a href="%s">Do something and redirect </a>' % url_for('do_something', next = request.full_path)

@app.route('/do_something')
def do_something():
    return redirect(request.args.get('next'))

 

為了避免next參數為空的情況,也可以加備選項,如果為空就重定向到hello視圖

return redirect(request.args.get('next', url_for('hello')))

 

為了覆蓋更全面,可以將查詢參數next和referrer兩種方式結合起來使用:

先獲取next參數,如果為空就嘗試獲取referer,如果仍然為空,就重定向到默認的hello視圖

因為在不同視圖執行這部分操作的代碼相同,我們可以創建一個通用的函數redirect_back()函數

在do_something視圖中調用這個函數

 

@app.route('/bar')
def bar():
    print "request.full_path:",request.full_path
    return '<h1>Bar page</h1><a href="%s">Do something and redirect </a>' % url_for('do_something', next = request.full_path)

def redirect_back(default = 'hello',**kwargs):
    for target in request.args.get('next'),request.referrer:
        if target:
            return redirect(target)
    return redirect(url_for(default,**kwargs))

@app.route('/do_something_and_redirect')
def do_something():
    return redirect_back()

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

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM