Skip to content

Instantly share code, notes, and snippets.

@lizhiwei
Created December 10, 2013 04:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save lizhiwei/7885684 to your computer and use it in GitHub Desktop.
Save lizhiwei/7885684 to your computer and use it in GitHub Desktop.
HTTP 206 (Partial Content) For Flask
import mimetypes
import os
import re
from flask import request, send_file, Response
@app.after_request
def after_request(response):
response.headers.add('Accept-Ranges', 'bytes')
return response
def send_file_partial(path):
"""
Simple wrapper around send_file which handles HTTP 206 Partial Content
(byte ranges)
TODO: handle all send_file args, mirror send_file's error handling
(if it has any)
"""
range_header = request.headers.get('Range', None)
if not range_header: return send_file(path)
size = os.path.getsize(path)
byte1, byte2 = 0, None
m = re.search('(\d+)-(\d*)', range_header)
g = m.groups()
if g[0]: byte1 = int(g[0])
if g[1]: byte2 = int(g[1])
length = size - byte1
if byte2 is not None:
length = byte2 - byte1
data = None
with open(path, 'rb') as f:
f.seek(byte1)
data = f.read(length)
rv = Response(data,
206,
mimetype=mimetypes.guess_type(path)[0],
direct_passthrough=True)
rv.headers.add('Content-Range', 'bytes {0}-{1}/{2}'.format(byte1, byte1 + length - 1, size))
return rv
@dimaqq
Copy link

dimaqq commented Jul 15, 2016

Length calculation is wrong in this gist.
0-0 means 1 byte (at index 0).

@marcoslin
Copy link

per @dimaqq, line 34 should be: length = byte2 + 1 - byte1 instead of length = byte2 - byte1.

@tanveer-sayyed
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment