make use of range requests if available in werkzeug (#2031)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* make use of range requests if available in werkzeug * different logic for testing werkzeug functionality
authored by Joël Charles · committed by Markus Unterwaditzer · parent f3d661d · Browse files · 3 files·+93 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+93 added−9 removed
- tests:+65 added−0 removed
- other:+28 added−9 removed
Provenance
- Commit
7186a5a- Tree
9754262- Author
Joël Charles <joel.charles91@gmail.com>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent
f3d661d
3 files changed+93 added−9 removed
modified:flask/helpers.py+27 added-9 removed
23 unmodified lines24 from werkzeug.urls import url_quote25 except ImportError:26 from urlparse import quote as url_quote27 28-from werkzeug.datastructures import Headers29-from werkzeug.exceptions import BadRequest, NotFound28+from werkzeug.datastructures import Headers, Range29+from werkzeug.exceptions import BadRequest, NotFound, \30+ RequestedRangeNotSatisfiable31 32 # this was moved in 0.733 try:34 from werkzeug.wsgi import wrap_file411 unmodified lines446 447 ETags will also be attached automatically if a `filename` is provided. You448 can turn this off by setting `add_etags=False`.449 450+ If `conditional=True` and `filename` is provided, this method will try to451+ upgrade the response stream to support range requests. This will allow452+ the request to be answered with partial content response.453+454 Please never pass filenames to this function from user sources;455 you should use :func:`send_from_directory` instead.456 457 .. versionadded:: 0.246 unmodified lines504 a :class:`~datetime.datetime` or timestamp.505 If a file was passed, this overrides its mtime.506 """507 mtime = None508+ fsize = None509 if isinstance(filename_or_fp, string_types):510 filename = filename_or_fp511 if not os.path.isabs(filename):512 filename = os.path.join(current_app.root_path, filename)27 unmodified lines540 if current_app.use_x_sendfile and filename:541 if file is not None:542 file.close()543 headers['X-Sendfile'] = filename538- headers['Content-Length'] = os.path.getsize(filename)544+ fsize = os.path.getsize(filename)545+ headers['Content-Length'] = fsize546 data = None547 else:548 if file is None:549 file = open(filename, 'rb')550 mtime = os.path.getmtime(filename)544- headers['Content-Length'] = os.path.getsize(filename)551+ fsize = os.path.getsize(filename)552+ headers['Content-Length'] = fsize553 data = wrap_file(request.environ, file)554 555 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,556 direct_passthrough=True)25 unmodified lines582 except OSError:583 warn('Access %s failed, maybe it does not exist, so ignore etags in '584 'headers' % filename, stacklevel=2)585 578- if conditional:586+ if conditional:587+ if callable(getattr(Range, 'to_content_range_header', None)):588+ # Werkzeug supports Range Requests589+ # Remove this test when support for Werkzeug <0.12 is dropped590+ try:591+ rv = rv.make_conditional(request, accept_ranges=True,592+ complete_length=fsize)593+ except RequestedRangeNotSatisfiable:594+ file.close()595+ raise596+ else:597 rv = rv.make_conditional(request)580- # make sure we don't send x-sendfile for servers that581- # ignore the 304 status code for x-sendfile.582- if rv.status_code == 304:583- rv.headers.pop('x-sendfile', None)598+ # make sure we don't send x-sendfile for servers that599+ # ignore the 304 status code for x-sendfile.600+ if rv.status_code == 304:601+ rv.headers.pop('x-sendfile', None)602 return rv603 604 605 def safe_join(directory, *pathnames):355 unmodified linesmodified:tests/test_helpers.py+65 added
12 unmodified lines13 14 import os15 import uuid16 import datetime17+18 import flask19 from logging import StreamHandler20+from werkzeug.datastructures import Range21 from werkzeug.exceptions import BadRequest, NotFound22 from werkzeug.http import parse_cache_control_header, parse_options_header23 from werkzeug.http import http_date24 from flask._compat import StringIO, text_type438 unmodified lines463 rv = flask.send_file(f, mimetype='text/html')464 assert 'x-sendfile' not in rv.headers465 rv.close()466 467+ @pytest.mark.skipif(468+ not callable(getattr(Range, 'to_content_range_header', None)),469+ reason="not implement within werkzeug"470+ )471+ def test_send_file_range_request(self):472+ app = flask.Flask(__name__)473+474+ @app.route('/')475+ def index():476+ return flask.send_file('static/index.html', conditional=True)477+478+ c = app.test_client()479+480+ rv = c.get('/', headers={'Range': 'bytes=4-15'})481+ assert rv.status_code == 206482+ with app.open_resource('static/index.html') as f:483+ assert rv.data == f.read()[4:16]484+ rv.close()485+486+ rv = c.get('/', headers={'Range': 'bytes=4-'})487+ assert rv.status_code == 206488+ with app.open_resource('static/index.html') as f:489+ assert rv.data == f.read()[4:]490+ rv.close()491+492+ rv = c.get('/', headers={'Range': 'bytes=4-1000'})493+ assert rv.status_code == 206494+ with app.open_resource('static/index.html') as f:495+ assert rv.data == f.read()[4:]496+ rv.close()497+498+ rv = c.get('/', headers={'Range': 'bytes=-10'})499+ assert rv.status_code == 206500+ with app.open_resource('static/index.html') as f:501+ assert rv.data == f.read()[-10:]502+ rv.close()503+504+ rv = c.get('/', headers={'Range': 'bytes=1000-'})505+ assert rv.status_code == 416506+ rv.close()507+508+ rv = c.get('/', headers={'Range': 'bytes=-'})509+ assert rv.status_code == 416510+ rv.close()511+512+ rv = c.get('/', headers={'Range': 'somethingsomething'})513+ assert rv.status_code == 416514+ rv.close()515+516+ last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(517+ os.path.join(app.root_path, 'static/index.html'))).replace(518+ microsecond=0)519+520+ rv = c.get('/', headers={'Range': 'bytes=4-15',521+ 'If-Range': http_date(last_modified)})522+ assert rv.status_code == 206523+ rv.close()524+525+ rv = c.get('/', headers={'Range': 'bytes=4-15', 'If-Range': http_date(526+ datetime.datetime(1999, 1, 1))})527+ assert rv.status_code == 200528+ rv.close()529+530 def test_attachment(self):531 app = flask.Flask(__name__)532 with app.test_request_context():533 with open(os.path.join(app.root_path, 'static/index.html')) as f:352 unmodified linesmodified:CHANGES+1 added
16 unmodified lines17 a Internal Server Error (pull request ``#2006``).18 - Correctly invoke response handlers for both regular request dispatching as19 well as error handlers.20 - Disable logger propagation by default for the app logger.21+- Add support for range requests in ``send_file``.22 23 Version 0.11.224 --------------25 572 unmodified lines