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
Provenance
- Commit
71e10be- Tree
bf1706a- Author
Markus Unterwaditzer <markus@unterwaditzer.net>- Committer
GitHub <noreply@github.com>- Parent
3313b8b
4 files changed+103 added−30 removed
modified:docs/upgrading.rst+39 added-1 removed
17 unmodified lines18 providing the ``--upgrade`` parameter::19 20 $ pip install --upgrade Flask21 22-.. _upgrading-to-10:22+.. _upgrading-to-012:23 24+Version 0.1225+------------26+27+Changes to send_file28+````````````````````29+30+The ``filename`` is no longer automatically inferred from file-like objects.31+This means that the following code will no longer automatically have32+``X-Sendfile`` support, etag generation or MIME-type guessing::33+34+ response = send_file(open('/path/to/file.txt'))35+36+Any of the following is functionally equivalent::37+38+ fname = '/path/to/file.txt'39+40+ # Just pass the filepath directly41+ response = send_file(fname)42+43+ # Set the MIME-type and ETag explicitly44+ response = send_file(open(fname), mimetype='text/plain')45+ response.set_etag(...)46+47+ # 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(...)51+52+The reason for this is that some file-like objects have a invalid or even53+misleading ``name`` attribute. Silently swallowing errors in such cases was not54+a satisfying solution.55+56+Additionally the default of falling back to ``application/octet-stream`` has57+been removed. If Flask can't guess one or the user didn't provide one, the58+function fails.59+60+.. _upgrading-to-011:61+62 Version 0.1163 ------------64 65 0.11 is an odd release in the Flask release cycle because it was supposed407 unmodified linesmodified:flask/helpers.py+39 added-17 removed
435 unmodified lines436 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``.439 440- 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.445 446+ ETags will also be attached automatically if a `filename` is provided. You447+ can turn this off by setting `add_etags=False`.448+449 Please never pass filenames to this function from user sources;450 you should use :func:`send_from_directory` instead.451 452 .. versionadded:: 0.211 unmodified lines464 .. versionchanged:: 0.9465 cache_timeout pulls its default from application config, when None.466 467 .. 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`.471 472+ .. versionchanged:: 0.12473+ The `attachment_filename` is preferred over `filename` for MIME-type474+ detection.475+476 :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 lines501 """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 = None513 498- 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]517 518+ 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+ )529+530 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)537 538 if current_app.use_x_sendfile and filename:408 unmodified linesmodified:tests/test_helpers.py+21 added-10 removed
382 unmodified lines383 last_modified = datetime.datetime(1999, 1, 1)384 385 @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')390 391 c = app.test_client()392 rv = c.get('/')393 assert rv.last_modified == last_modified394 395+ def test_send_file_object_without_mimetype(self):396+ app = flask.Flask(__name__)397+398+ with app.test_request_context():399+ with pytest.raises(ValueError) as excinfo:400+ flask.send_file(StringIO("LOL"))401+402+ assert 'Unable to infer MIME-type' in str(excinfo)403+ assert 'no filename is available' in str(excinfo)404+405 def test_send_file_object(self):406 app = flask.Flask(__name__)407 408 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 lines417 app.use_x_sendfile = True418 419 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()425 426 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 lines438 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 lines455 app.use_x_sendfile = True456 457 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()462 463 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 linesmodified:CHANGES+4 added-2 removed
5 unmodified lines6 Version 0.127 ------------8 9 - 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``).16 17 Version 0.11.2574 unmodified lines