partial-text.py (2051B)
1 """ 2 This generates a partial response for a 100-byte text file. 3 """ 4 import re 5 6 from wptserve.utils import isomorphic_decode 7 8 def main(request, response): 9 total_length = int(request.GET.first(b'length', b'100')) 10 partial_code = int(request.GET.first(b'partial', b'206')) 11 content_type = request.GET.first(b'type', b'text/plain') 12 range_header = request.headers.get(b'Range', b'') 13 14 # Send a 200 if there is no range request 15 if not range_header: 16 to_send = ''.zfill(total_length) 17 response.headers.set(b"Content-Type", content_type) 18 response.headers.set(b"Cache-Control", b"no-cache") 19 response.headers.set(b"Content-Length", total_length) 20 response.content = to_send 21 return 22 23 # Simple range parsing, requires specifically "bytes=xxx-xxxx" 24 range_header_match = re.search(r'^bytes=(\d*)-(\d*)$', isomorphic_decode(range_header)) 25 start, end = range_header_match.groups() 26 start = int(start) 27 end = int(end) if end else total_length 28 length = end - start 29 30 # Error the request if the range goes beyond the length 31 if length <= 0 or end > total_length: 32 response.set_error(416, u"Range Not Satisfiable") 33 # set_error sets the MIME type to application/json, which - for a 34 # no-cors media request - will be blocked by ORB. We'll just force 35 # the expected MIME type here, whichfixes the test, but doesn't make 36 # sense in general. 37 response.headers = [(b"Content-Type", content_type)] 38 response.write() 39 return 40 41 # Generate a partial response of the requested length 42 to_send = ''.zfill(length) 43 response.headers.set(b"Content-Type", content_type) 44 response.headers.set(b"Accept-Ranges", b"bytes") 45 response.headers.set(b"Cache-Control", b"no-cache") 46 response.status = partial_code 47 48 content_range = b"bytes %d-%d/%d" % (start, end, total_length) 49 50 response.headers.set(b"Content-Range", content_range) 51 response.headers.set(b"Content-Length", length) 52 53 response.content = to_send