response.raw() 功能:Sanic 返回二进制数据给浏览器。
response.raw() 语法
def raw(
body,
status=200, headers=None,
content_type="application/octet-stream;
):
response.raw() 参数
- body:响应要返回的
bytes
字符串,不是str
; - status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
- content_type:纯文本的content type,不要修改;
raw()
跟text()
非常像,不同的是,raw()
传入的body
必须是bytes
字符串(即,str
编码后的结果)。这里面,body
是必需的参数,可以通过传入headers
来自定义响应头,其它参数不要修改。
比如,自定义响应头headers:
return raw('Welcom to 猿人学Python',
headers={'X-Serverd-By': 'YuanRenXue Python'})
response.raw() 返回值
返回一个HTTPResponse
类的实例。多数情况下,路由函数直接返回这个实例。当需要再进一步处理响应(比如,设置响应cookies)时,要把它赋值给一个变量。
response.raw() 例子
from sanic import Sanic
from sanic import response
app = Sanic()
@app.route('/raw')
async def raw(request):
msg = 'Welcom to 猿人学Python'
return response.raw(
msg.encode('utf8'),
headers={'X-Serverd-By': 'YuanRenXue Python'}
)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888)
注意:传入的字符串必须是编码后的bytes
。
通过curl
来查看raw响应:
curl -i http://127.0.0.1:8888/raw
结果如下,可以看到我们自定义的headersX-Serverd-By: YuanRenXue Python
:
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
X-Serverd-By: YuanRenXue Python
Content-Length: 25
Content-Type: application/octet-stream
Welcom to 猿人学Python
请注意Content-Type
与其它响应函数的不同。

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