-
-
Save skakri/def856b0e933b3b499a1 to your computer and use it in GitHub Desktop.
HTTP 206 (Partial Content) For Flask
This file contains hidden or 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, filename, **kwargs): | |
range_header = request.headers.get('Range', None) | |
if not range_header: | |
return send_from_directory(path, filename, **kwargs) | |
full_filename = path + '/' + filename | |
size = os.path.getsize(full_filename) | |
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(full_filename, 'rb') as f: | |
f.seek(byte1) | |
data = f.read(length) | |
rv = Response( | |
data, | |
206, | |
mimetype=mimetypes.guess_type(full_filename)[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
line 33 should be:
length = byte2 + 1 - byte1
instead oflength = byte2 - byte1
.