Skip to content

Commit

Permalink
Add file streaming section to the streaming documentation page
Browse files Browse the repository at this point in the history
  • Loading branch information
andreymal committed Apr 20, 2019
1 parent 6be12ba commit 9615e37
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions docs/sanic/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
```

0 comments on commit 9615e37

Please sign in to comment.