From 4eb1af0b1147adb53a848c1b3053555033a12759 Mon Sep 17 00:00:00 2001 From: Jon Bergli Heier Date: Fri, 29 Jul 2011 19:12:22 +0200 Subject: Support ranges using X-Sendfile2. --- fbin.py | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/fbin.py b/fbin.py index e0d70d8..106f8e4 100755 --- a/fbin.py +++ b/fbin.py @@ -1,7 +1,7 @@ #!/usr/bin/env python2 import templates -import settings, db, os, random, datetime, shutil, mimetypes, cgi, tempfile, hashlib, Cookie +import settings, db, os, random, datetime, shutil, mimetypes, cgi, tempfile, hashlib, Cookie, urllib from PIL import Image base62_alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' @@ -142,9 +142,24 @@ class Application(object): start_response('304 Not Modified', [('Last-Modified', file.date.strftime(rfc1123_format))]) return [] + do_range = 'HTTP_RANGE' in environ + if do_range: + file_range = environ['HTTP_RANGE'] + mime = mimetypes.guess_type(file.filename, strict = False)[0] or 'application/octet-stream' if settings.use_xsendfile: - start_response('200 OK', [('X-Sendfile', filename.encode('utf8')), ('Last-Modified', file.date.strftime(rfc1123_format))]) + headers = [('Last-Modified', file.date.strftime(rfc1123_format))] + if do_range: + r = file_range.split('bytes=')[1] + headers.append(('X-Sendfile2', '{filename} {range}'.format(filename = urllib.quote(filename.encode('utf8')), range = r))) + if r.endswith('-'): + r += str(os.path.getsize(filename)-1) + headers.append(('Content-Range', 'bytes {r}/{size}'.format(r = r, size = os.path.getsize(filename)))) + status = '206 Partial Content' + else: + headers.append(('X-Sendfile', filename.encode('utf8'))) + status = '200 OK' + start_response(status, headers) return [] start_response('200 OK', [('Content-Type', mime), ('Content-Length', str(os.path.getsize(filename))), -- cgit v1.2.3