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

Sanic教程 2019-03-23 21:49:04 阅读(45410) 评论(0)

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.cn/',
    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.cn/',
        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.cn/
Content-Length: 0
Content-Type: text/html; charset=utf-8

请注意HTTP/1.1 302 FoundLocation与其它响应函数的不同。

猿人学banner宣传图

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。

***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***

说点什么吧...