Fastapi: Using StreamingResponse to stream videos with seeking capabilities

Created on 11 Apr 2020  路  5Comments  路  Source: tiangolo/fastapi

First check

  • I checked StreamingResponse (along with the related issues) and can stream a video properly.

Description

I was wondering if it was possible using fastapi to use "StreamingResponse" not only to stream a video, but to be able to seek (with byte-range i guess ?)

Additional context

I am trying to reimplement a similar software to peerflix (https://github.com/mafintosh/peerflix), which basically downloads a content, and stream it then. It uses nodejs, which I would like to avoid, and i was wondering if it was possible to do such thing with fastapi. (some people achieved it with other technology : https://github.com/romanvm/kodi.yatp )

answered question

All 5 comments

My bad I think i managed to solve it.
I will leave that here for people that may be looking for an answer :

  • You need to return a status_code=206 in your StreamingResponse, and also set the approriate headers to enable range downloading:
headers = {
    "Accept-Ranges": "bytes",
    "Content-Length": str(sz),
    "Content-Range": F"bytes {asked}-{sz-1}/{sz}",
}
response =  StreamingResponse(streaming_file(file_path, CS, asked), headers=headers,

Not sure if there is anything else to add, but it seems like it's working here.

Could you provide a full code example on how you achieved this? I need to implement the exact same thing (serving a folder of videos that can be streamed).
The StaticFiles way almost works (it works with firefox), but fails in chrome because it returns the 200 response code instead of 206, which then makes chrome think that it can't do range requests.

I currently have the same issue with Chrome, did not really dug in that sense to be honest. (I'm serving files to be opened with VLC, so browser do not really matter for me)

Thanks for reporting back @0xAcid .

You should probably be able to create a subclass of StaticFiles returning the status code you need, I guess...

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

Was this page helpful?
0 / 5 - 0 ratings