Skip to content
Myr

Properly remove f.name usage in send_file (#1988)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Properly remove f.name usage in send_file * Update changelogs * Fix tests

authored by Markus Unterwaditzer · committed by GitHub · parent 3313b8b · Browse files · 4 files+103 added−30 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+103 added−30 removed

  • tests:+21 added−10 removed
  • other:+82 added−20 removed

4 files+103 added−30 removed

modified:docs/upgrading.rst+39 added-1 removed
17 unmodified lines
18providing the ``--upgrade`` parameter::1920 $ pip install --upgrade Flask2122.. _upgrading-to-10:22.. _upgrading-to-012:2324Version 0.1225------------2627Changes to send_file28````````````````````2930The ``filename`` is no longer automatically inferred from file-like objects.31This means that the following code will no longer automatically have32``X-Sendfile`` support, etag generation or MIME-type guessing::3334 response = send_file(open('/path/to/file.txt'))3536Any of the following is functionally equivalent::3738 fname = '/path/to/file.txt'3940 # Just pass the filepath directly41 response = send_file(fname)4243 # Set the MIME-type and ETag explicitly44 response = send_file(open(fname), mimetype='text/plain')45 response.set_etag(...)4647 # Set `attachment_filename` for MIME-type guessing48 # ETag still needs to be manually set49 response = send_file(open(fname), attachment_filename=fname)50 response.set_etag(...)5152The reason for this is that some file-like objects have a invalid or even53misleading ``name`` attribute. Silently swallowing errors in such cases was not54a satisfying solution.5556Additionally the default of falling back to ``application/octet-stream`` has57been removed. If Flask can't guess one or the user didn't provide one, the58function fails.5960.. _upgrading-to-011:6162Version 0.1163------------64650.11 is an odd release in the Flask release cycle because it was supposed
407 unmodified lines
modified:flask/helpers.py+39 added-17 removed
435 unmodified lines
436 you can set the application's :attr:`~Flask.use_x_sendfile` attribute437 to ``True`` to directly emit an ``X-Sendfile`` header. This however438 requires support of the underlying webserver for ``X-Sendfile``.439440 You must explicitly provide the mimetype for the filename or file object.440 By default it will try to guess the mimetype for you, but you can441 also explicitly provide one. For extra security you probably want442 to send certain files as attachment (HTML for instance). The mimetype443 guessing requires a `filename` or an `attachment_filename` to be444 provided.445446 ETags will also be attached automatically if a `filename` is provided. You447 can turn this off by setting `add_etags=False`.448449 Please never pass filenames to this function from user sources;450 you should use :func:`send_from_directory` instead.451452 .. versionadded:: 0.2
11 unmodified lines
464 .. versionchanged:: 0.9465 cache_timeout pulls its default from application config, when None.466467 .. versionchanged:: 0.12461 mimetype guessing and etag support removed for file objects.462 If no mimetype or attachment_filename is provided, application/octet-stream463 will be used.468 The filename is no longer automatically inferred from file objects. If469 you want to use automatic mimetype and etag support, pass a filepath via470 `filename_or_fp` or `attachment_filename`.471472 .. versionchanged:: 0.12473 The `attachment_filename` is preferred over `filename` for MIME-type474 detection.475476 :param filename_or_fp: the filename of the file to send in `latin-1`.477 This is relative to the :attr:`~Flask.root_path`478 if a relative path is specified.479 Alternatively a file object might be provided in480 which case ``X-Sendfile`` might not work and fall481 back to the traditional method. Make sure that the482 file pointer is positioned at the start of data to483 send before calling :func:`send_file`.473 :param mimetype: the mimetype of the file if provided, otherwise474 auto detection happens.484 :param mimetype: the mimetype of the file if provided. If a file path is485 given, auto detection happens as fallback, otherwise an486 error will be raised.487 :param as_attachment: set to ``True`` if you want to send this file with488 a ``Content-Disposition: attachment`` header.489 :param attachment_filename: the filename for the attachment if it490 differs from the file's filename.
10 unmodified lines
501 """502 mtime = None503 if isinstance(filename_or_fp, string_types):504 filename = filename_or_fp505 if not os.path.isabs(filename):506 filename = os.path.join(current_app.root_path, filename)507 file = None508 if attachment_filename is None:509 attachment_filename = os.path.basename(filename)510 else:511 file = filename_or_fp496 filename = getattr(file, 'name', None)512 filename = None513498 if filename is not None:499 if not os.path.isabs(filename):500 filename = os.path.join(current_app.root_path, filename)501 if mimetype is None and (filename or attachment_filename):502 mimetype = mimetypes.guess_type(filename or attachment_filename)[0]514 if mimetype is None:504 mimetype = 'application/octet-stream'515 if attachment_filename is not None:516 mimetype = mimetypes.guess_type(attachment_filename)[0]517518 if mimetype is None:519 if attachment_filename is not None:520 raise ValueError(521 'Unable to infer MIME-type from filename {!r}, please '522 'pass one explicitly.'.format(mimetype_filename)523 )524 raise ValueError(525 'Unable to infer MIME-type because no filename is available. '526 'Please set either `attachment_filename`, pass a filepath to '527 '`filename_or_fp` or set your own MIME-type via `mimetype`.'528 )529530 headers = Headers()531 if as_attachment:532 if attachment_filename is None:509 if filename is None:510 raise TypeError('filename unavailable, required for '511 'sending as attachment')533 raise TypeError('filename unavailable, required for '534 'sending as attachment')512 attachment_filename = os.path.basename(filename)535 headers.add('Content-Disposition', 'attachment',536 filename=attachment_filename)537538 if current_app.use_x_sendfile and filename:
408 unmodified lines
modified:tests/test_helpers.py+21 added-10 removed
382 unmodified lines
383 last_modified = datetime.datetime(1999, 1, 1)384385 @app.route('/')386 def index():387 return flask.send_file(StringIO("party like it's"), last_modified=last_modified)387 return flask.send_file(StringIO("party like it's"),388 last_modified=last_modified,389 mimetype='text/plain')390391 c = app.test_client()392 rv = c.get('/')393 assert rv.last_modified == last_modified394395 def test_send_file_object_without_mimetype(self):396 app = flask.Flask(__name__)397398 with app.test_request_context():399 with pytest.raises(ValueError) as excinfo:400 flask.send_file(StringIO("LOL"))401402 assert 'Unable to infer MIME-type' in str(excinfo)403 assert 'no filename is available' in str(excinfo)404405 def test_send_file_object(self):406 app = flask.Flask(__name__)407408 with app.test_request_context():409 with open(os.path.join(app.root_path, 'static/index.html'), mode='rb') as f:398 rv = flask.send_file(f)410 rv = flask.send_file(f, mimetype='text/html')411 rv.direct_passthrough = False412 with app.open_resource('static/index.html') as f:413 assert rv.data == f.read()414 assert rv.mimetype == 'text/html'
2 unmodified lines
417 app.use_x_sendfile = True418419 with app.test_request_context():420 with open(os.path.join(app.root_path, 'static/index.html')) as f:409 rv = flask.send_file(f)421 rv = flask.send_file(f, mimetype='text/html')422 assert rv.mimetype == 'text/html'411 assert 'x-sendfile' in rv.headers412 assert rv.headers['x-sendfile'] == \413 os.path.join(app.root_path, 'static/index.html')423 assert 'x-sendfile' not in rv.headers424 rv.close()425426 app.use_x_sendfile = False427 with app.test_request_context():428 f = StringIO('Test')419 rv = flask.send_file(f)429 rv = flask.send_file(f, mimetype='application/octet-stream')430 rv.direct_passthrough = False431 assert rv.data == b'Test'432 assert rv.mimetype == 'application/octet-stream'433 rv.close()
4 unmodified lines
438 def __getattr__(self, name):439 return getattr(self._io, name)440 f = PyStringIO('Test')441 f.name = 'test.txt'432 rv = flask.send_file(f)442 rv = flask.send_file(f, attachment_filename=f.name)443 rv.direct_passthrough = False444 assert rv.data == b'Test'445 assert rv.mimetype == 'text/plain'446 rv.close()
8 unmodified lines
455 app.use_x_sendfile = True456457 with app.test_request_context():458 f = StringIO('Test')449 rv = flask.send_file(f)459 rv = flask.send_file(f, mimetype='text/html')460 assert 'x-sendfile' not in rv.headers461 rv.close()462463 def test_attachment(self):464 app = flask.Flask(__name__)465 with app.test_request_context():466 with open(os.path.join(app.root_path, 'static/index.html')) as f:457 rv = flask.send_file(f, as_attachment=True)467 rv = flask.send_file(f, as_attachment=True,468 attachment_filename='index.html')469 value, options = \470 parse_options_header(rv.headers['Content-Disposition'])471 assert value == 'attachment'472 rv.close()
346 unmodified lines
modified:CHANGES+4 added-2 removed
5 unmodified lines
6Version 0.127------------89- the cli command now responds to `--version`.10- Mimetype guessing for ``send_file`` has been removed, as per issue ``#104``.11 See pull request ``#1849``.10- Mimetype guessing and ETag generation for file-like objects in ``send_file``11 has been removed, as per issue ``#104``. See pull request ``#1849``.12- Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to13 ``application/octet-stream``. See pull request ``#1988``.14- Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``15 (pull request ``#1730``).1617Version 0.11.2
574 unmodified lines