-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.py
32 lines (26 loc) · 1012 Bytes
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from pathlib import Path
from fastapi import FastAPI
from fastapi import Request, Response
from fastapi import Header
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
CHUNK_SIZE = 1024*1024
video_path = Path("video.mp4")
@app.get("/")
async def read_root(request: Request):
return templates.TemplateResponse("index.htm", context={"request": request})
@app.get("/video")
async def video_endpoint(range: str = Header(None)):
start, end = range.replace("bytes=", "").split("-")
start = int(start)
end = int(end) if end else start + CHUNK_SIZE
with open(video_path, "rb") as video:
video.seek(start)
data = video.read(end - start)
filesize = str(video_path.stat().st_size)
headers = {
'Content-Range': f'bytes {str(start)}-{str(end)}/{filesize}',
'Accept-Ranges': 'bytes'
}
return Response(data, status_code=206, headers=headers, media_type="video/mp4")