response.redirect() 功能:Sanic 返回一个重定向URL让浏览器去访问。它是通过在响应头headers里面设置 Location 来实现的。
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的Location
为to
告诉浏览器重定向,它只包含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 Found
和Location
与其它响应函数的不同。

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***
说点什么吧...