From 9615e37ef9e2f6a13a9925974b0b701c9b03ef29 Mon Sep 17 00:00:00 2001 From: andreymal Date: Sat, 20 Apr 2019 23:50:19 +0300 Subject: [PATCH] Add file streaming section to the streaming documentation page --- docs/sanic/streaming.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/sanic/streaming.md b/docs/sanic/streaming.md index 53d23ea3..29e28bf7 100644 --- a/docs/sanic/streaming.md +++ b/docs/sanic/streaming.md @@ -119,3 +119,25 @@ async def index(request): ``` If a client supports HTTP/1.1, Sanic will use [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding); you can explicitly enable or disable it using `chunked` option of the `stream` function. + +## File Streaming + +Sanic provides `sanic.response.file_stream` function that is useful when you want to send a large file. It returns a `StreamingHTTPResponse` object and will use chunked transfer encoding by default; for this reason Sanic doesn't add `Content-Length` HTTP header in the response. If you want to use this header, you can disable chunked transfer encoding and add it manually: + +```python +from aiofiles import os as async_os +from sanic.response import file_stream + +@app.route("/") +async def index(request): + file_path = "/srv/www/whatever.png" + + file_stat = await async_os.stat(file_path) + headers = {"Content-Length": str(file_stat.st_size)} + + return await file_stream( + file_path, + headers=headers, + chunked=False, + ) +```