Created
December 10, 2013 04:20
-
-
Save lizhiwei/7885684 to your computer and use it in GitHub Desktop.
HTTP 206 (Partial Content) For Flask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
per @dimaqq, line 34 should be:
length = byte2 + 1 - byte1
instead oflength = byte2 - byte1
.