response.stream() 功能:Sanic 返回流数据给浏览器。流数据的意思就是,不是一次性把所有数据返回,而是一部分一部分地返回。
response.stream() 语法
def stream(
streaming_fn,
status=200,
headers=None,
content_type="text/plain; charset=utf-8",
):
response.stream() 参数
- streaming_fn:用于流响应写数据的协程函数;
- status:默认 http 状态码200,正常返回不要修改;
- headers:自定义 http 响应头;
- content_type:纯文本的content type,按需修改;
这里面,streaming_fn
是必需的参数,可以通过传入headers
来自定义响应头,其它参数不要修改。
response.stream() 返回值
返回一个StreamingHTTPResponse
类的实例。
response.stream() 例子
import asyncio
import time
from sanic import Sanic
from sanic import response
app = Sanic()
@app.route('/stream')
async def streaming(request):
async def streaming_fn(response):
await response.write('Welcom to @{}\n'.format(time.strftime('%H:%M:%S')))
await asyncio.sleep(3)
await response.write('猿人学Python @{}\n'.format(time.strftime('%H:%M:%S')))
return response.stream(
streaming_fn,
headers={'X-Serverd-By': 'YuanRenXue Python'}
)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8888)
通过curl
来查看stream响应:
curl -i http://127.0.0.1:8888/stream
结果如下,可以看到我们自定义的headersX-Serverd-By: YuanRenXue Python
:
HTTP/1.1 200 OK
Keep-Alive: 5
X-Serverd-By: YuanRenXue Python
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8
Welcom to @12:05:21
猿人学Python @12:05:24
为了演示流数据的“流性”,也就是一点一点的返回数据,我们在两次异步写操作之间加了一个停顿3秒的操作。通过curl或浏览器查看结果时,可以看到第一个写操作是在12:05:21
这个时间发生,3秒以后才会看到第二次写操作的内容。两者写入的时间戳正好相差3秒。

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