Created
December 10, 2013 03:01
-
-
Save lizhiwei/7885108 to your computer and use it in GitHub Desktop.
response to a range request with python Flask framework
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
from flask import Response, request | |
from werkzeug.datastructures import Headers | |
from time import time | |
from re import findall | |
def send_file(musicFile , cachetimout, stream=True): | |
headers = Headers() | |
headers.add('Content-Disposition', 'attachment', filename=musicFile.filename) | |
headers.add('Content-Transfer-Encoding','binary') | |
status = 200 | |
size = getsize(musicFile.path) | |
begin = 0; | |
end = size-1; | |
if request.headers.has_key("Range") and rangerequest: | |
status = 206 | |
headers.add('Accept-Ranges','bytes') | |
ranges = findall(r"\d+", request.headers["Range"]) | |
begin = int( ranges[0] ) | |
if len(ranges)>1: | |
end = int( ranges[1] ) | |
headers.add('Content-Range','bytes %s-%s/%s' % (str(begin),str(end),str(end-begin)) ) | |
headers.add('Content-Length',str((end-begin)+1)) | |
#Add mimetype | |
mimetypes = {u"mp3":"audio/mpeg",u"ogg":"audio/ogg"} | |
if stream==True: | |
mimetype = mimetypes[musicFile.filetype] | |
else: | |
mimetype = "application/octet-stream" | |
response = Response( file(musicFile.path), status=status, mimetype=mimetype, headers=headers, direct_passthrough=True) | |
#enable browser file caching with etags | |
response.cache_control.public = True | |
response.cache_control.max_age = int(cachetimout) | |
response.last_modified = int(musicFile.changetime) | |
response.expires = int( time() + int(cachetimout) ) | |
response.set_etag('%s%s' % ( musicFile.id,musicFile.changetime )) | |
response.make_conditional(request) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rangerequest
on line 18 is undefined.