python
69 lines · 8 steps
HTTP range requests for video streaming in Flask
A Flask blueprint serves media files in seekable chunks by honoring the HTTP Range header.
Explained by
highlit
1import os
2import re
3from flask import Blueprint, request, Response, abort
4
5video_bp = Blueprint("video", __name__)
6
7RANGE_RE = re.compile(r"bytes=(\d*)-(\d*)")
8CHUNK_SIZE = 1024 * 1024
9
10
11def parse_range(header, file_size):
12 match = RANGE_RE.fullmatch(header.strip())
13 if not match:
14 return None
15 start_raw, end_raw = match.groups()
16 if start_raw == "":
17 if end_raw == "":
18 return None
19 length = min(int(end_raw), file_size)
20 return file_size - length, file_size - 1
21 start = int(start_raw)
22 end = int(end_raw) if end_raw else file_size - 1
23 end = min(end, file_size - 1)
24 if start > end:
25 return None
26 return start, end
27
28
29@video_bp.route("/media/<path:filename>")
30def stream_media(filename):
31 path = os.path.join(video_bp.root_path, "media", filename)
32 if not os.path.isfile(path):
33 abort(404)
34
35 file_size = os.path.getsize(path)
36 range_header = request.headers.get("Range")
37
38 if not range_header:
39 return Response(_read(path, 0, file_size - 1), mimetype="video/mp4",
40 headers={"Accept-Ranges": "bytes", "Content-Length": str(file_size)})
41
42 rng = parse_range(range_header, file_size)
43 if rng is None:
44 return Response(status=416, headers={"Content-Range": f"bytes */{file_size}"})
45
46 start, end = rng
47 length = end - start + 1
48 return Response(
49 _read(path, start, end),
50 status=206,
51 mimetype="video/mp4",
52 headers={
53 "Content-Range": f"bytes {start}-{end}/{file_size}",
54 "Accept-Ranges": "bytes",
55 "Content-Length": str(length),
56 },
57 )
58
59
60def _read(path, start, end):
61 with open(path, "rb") as fh:
62 fh.seek(start)
63 remaining = end - start + 1
64 while remaining > 0:
65 data = fh.read(min(CHUNK_SIZE, remaining))
66 if not data:
67 break
68 remaining -= len(data)
69 yield data
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Range requests let clients seek video without downloading the whole file, and the server signals support via Accept-Ranges and 206 responses.
- 2Parsing the Range header defensively — clamping bounds and returning 416 on garbage — keeps the endpoint robust against malformed input.
- 3Yielding fixed-size chunks from a generator streams large files with bounded memory instead of loading them entirely.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/http-range-requests-for-video-streaming-in-flask-explained-python-27f4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.