Sanic response redirect() 函式用法和示例

veelion發表於2019-03-23

response.redirect() 功能:Sanic 返回一個重定向URL讓瀏覽器去訪問。它是通過在響應頭headers裡面設定 Location 來實現的。

Sanic response.redirect() 函式

response.redirect() 語法

def redirect(
    to,
    headers=None, 
    status=302,
    content_type="text/html; charset=utf-8"
):

response.redirect() 引數

  • to:響應要返回的重定向URL字串;
  • status:預設 http 狀態碼302,正常返回不要修改;
  • headers:自定義 http 響應頭;
  • content_type:HTTP 響應頭的 content type,不要修改;

這裡面,to是必需的引數,可以通過傳入headers來自定義響應頭,其它引數不要修改。
比如,自定義響應頭headers:


return redirect(
    'https://www.yuanrenxue.com/',
    headers={'X-Serverd-By': 'YuanRenXue Python'}
)

response.redirect() 返回值

返回一個HTTPResponse類的例項。這個例項通過設定headers的Locationto告訴瀏覽器重定向,它只包含HTTP 響應頭,不包含響應體。

response.redirect() 例子

from sanic import Sanic
from sanic import response


app = Sanic()


@app.route('/redirect')
async def redirect(request):
    return response.redirect(
        'https://www.yuanrenxue.com/',
        headers={'X-Serverd-By': 'YuanRenXue Python'}
    )


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8888, debug=True)

通過curl來檢視redirect響應:

curl -i http://127.0.0.1:8888/redirect

結果如下,可以看到我們自定義的headersX-Serverd-By: YuanRenXue Python


HTTP/1.1 302 Found
Connection: keep-alive
Keep-Alive: 5
X-Serverd-By: YuanRenXue Python
Location: https://www.yuanrenxue.com/
Content-Length: 0
Content-Type: text/html; charset=utf-8

請注意HTTP/1.1 302 FoundLocation與其它響應函式的不同。

猿人學banner宣傳圖

我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。

***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***

相關文章