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

Sanic教程 2019-03-23 21:52:06 阅读(38887) 评论(0)

response.file_stream() 功能是:Sanic 返回文件流给浏览器。这个函数和file()都是返回文件,但是它的不同支出是边读边返回,每次返回一定大小的数据,而file()是一次性读完整个文件再返回给浏览器。很明显,如果文件很大时,文件流可以大大节省服务器的内存。

Sanic response.file_stream() 函数

response.file_stream() 语法

async def file_stream(
    location,
    status=200,
    chunk_size=4096,
    mime_type=None,
    headers=None,
    filename=None,
    _range=None,
):

response.file_stream() 参数

  • location:响应要返回的文件路径;
  • status:默认 http 状态码200,正常返回不要修改;
  • chunk_size:每次读取文件数据的大小;
  • mime_type: 返回文件的格式;
  • headers:自定义 http 响应头;
  • filename:如果传值则写入响应头headers的Content-Disposition
  • _range:指定文件的某一部分;

这里面,location是必需的参数;
可以通过传入headers来自定义响应头;
如果没有传入mime_type参数,其内部会使用模块mimetypesmimetypes.guess_type()函数通过filename来获得;
_range对象需要有四个属性:start, end, size, total来描述截取文件中的某一部分。

response.file_stream() 返回值

返回一个StreamingHTTPResponse类的实例。

response.file_stream() 例子

from sanic import Sanic
from sanic import response


app = Sanic()


@app.route('/file_stream')
async def large_file(request):
    return await response.file_stream(
        './big_file.jpg',
        headers={'X-Serverd-By': 'YuanRenXue Python'}
    )


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

通过echo创建一个假的jpg文件,其内容为“Welcom to 猿人学Python”,再通过curl来查看file_stream响应:

echo "Welcom to 猿人学Python" > ./big_file.jpg
curl -i http://127.0.0.1:8888/file_stream

结果如下,可以看到我们自定义的headersX-Serverd-By: YuanRenXue Python


HTTP/1.1 200 OK
Keep-Alive: 5
X-Serverd-By: YuanRenXue Python
Transfer-Encoding: chunked
Content-Type: image/jpeg

Welcom to 猿人学Python

下面是file()响应的结果:

HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
X-Serverd-By: YuanRenXue Python
Content-Length: 10
Content-Type: image/jpeg

Welcom to 猿人学Python

对比一下两者的响应头headers,注意file_stream()多了Transfer-Encoding,却少了Content-Length。这是因为,以流的形式每次只返回一个chunk,无法知道整个文件的大小。

猿人学banner宣传图

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

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

说点什么吧...