Skip to content
Myr

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

3 files+93 added−9 removed

modified:flask/helpers.py+27 added-9 removed
23 unmodified lines
24 from werkzeug.urls import url_quote25except ImportError:26 from urlparse import quote as url_quote2728from werkzeug.datastructures import Headers29from werkzeug.exceptions import BadRequest, NotFound28from werkzeug.datastructures import Headers, Range29from werkzeug.exceptions import BadRequest, NotFound, \30 RequestedRangeNotSatisfiable3132# this was moved in 0.733try:34 from werkzeug.wsgi import wrap_file
411 unmodified lines
446447 ETags will also be attached automatically if a `filename` is provided. You448 can turn this off by setting `add_etags=False`.449450 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.453454 Please never pass filenames to this function from user sources;455 you should use :func:`send_from_directory` instead.456457 .. versionadded:: 0.2
46 unmodified lines
504 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 lines
540 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)554555 rv = current_app.response_class(data, mimetype=mimetype, headers=headers,556 direct_passthrough=True)
25 unmodified lines
582 except OSError:583 warn('Access %s failed, maybe it does not exist, so ignore etags in '584 'headers' % filename, stacklevel=2)585578 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 rv603604605def safe_join(directory, *pathnames):
355 unmodified lines
modified:tests/test_helpers.py+65 added
12 unmodified lines
1314import os15import uuid16import datetime1718import flask19from logging import StreamHandler20from werkzeug.datastructures import Range21from werkzeug.exceptions import BadRequest, NotFound22from werkzeug.http import parse_cache_control_header, parse_options_header23from werkzeug.http import http_date24from flask._compat import StringIO, text_type
438 unmodified lines
463 rv = flask.send_file(f, mimetype='text/html')464 assert 'x-sendfile' not in rv.headers465 rv.close()466467 @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__)473474 @app.route('/')475 def index():476 return flask.send_file('static/index.html', conditional=True)477478 c = app.test_client()479480 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()485486 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()491492 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()497498 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()503504 rv = c.get('/', headers={'Range': 'bytes=1000-'})505 assert rv.status_code == 416506 rv.close()507508 rv = c.get('/', headers={'Range': 'bytes=-'})509 assert rv.status_code == 416510 rv.close()511512 rv = c.get('/', headers={'Range': 'somethingsomething'})513 assert rv.status_code == 416514 rv.close()515516 last_modified = datetime.datetime.fromtimestamp(os.path.getmtime(517 os.path.join(app.root_path, 'static/index.html'))).replace(518 microsecond=0)519520 rv = c.get('/', headers={'Range': 'bytes=4-15',521 'If-Range': http_date(last_modified)})522 assert rv.status_code == 206523 rv.close()524525 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()529530 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 lines
modified:CHANGES+1 added
16 unmodified lines
17 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``.2223Version 0.11.224--------------25
572 unmodified lines