response.file() 功能:Sanic 返回文件数据给浏览器,以此实现文件下载功能。

response.file() 语法
async def file(
    location,
    status=200,
    mime_type=None,
    headers=None,
    filename=None,
    _range=None,
):
读写文件是一个IO操作,所以这是一个异步函数,使用时记得加await。
response.file() 参数
- location:响应要返回的文件的路径;
 - status:默认 http 状态码200,正常返回不要修改;
 - mime_type:文件格式;
 - headers:自定义 http 响应头;
 - filename:如果传值则写入响应头headers的
Content-Disposition; _range:指定文件的某一部分;
这里面,location是必需的参数;
可以通过传入headers来自定义响应头;
如果没有传入mime_type参数,其内部会使用模块mimetypes的mimetypes.guess_type()函数通过filename来获得;
_range对象需要有四个属性:start, end, size, total来描述截取文件中的某一部分。
response.file() 返回值
返回一个HTTPResponse类的实例。多数情况下,路由函数直接返回这个实例。当需要再进一步处理响应(比如,设置响应cookies)时,要把它赋值给一个变量。
response.file() 例子
from sanic import Sanic
from sanic import response
app = Sanic()
@app.route('/file')
async def file(request):
    return await response.file(
        './welcom-to-猿人学.jpg',
        headers={'X-Serverd-By': 'YuanRenXue Python'}
    )
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8888, debug=True)
通过echo创建一个假的jpg文件,其内容为“Welcom to 猿人学Python”,再通过curl来查看file响应:
echo "Welcom to 猿人学Python" > ./welcom-to-猿人学.jpg
curl -i http://127.0.0.1:8888/file
结果如下,可以看到我们自定义的headersX-Serverd-By: YuanRenXue Python:
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
 
我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***

说点什么吧...