Skip to content
Myr

send_file doesn't allow StringIO

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

authored by David Lord · committed by David Lord · parent 2659f0a · Browse files · 3 files+101 added−93 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+101 added−93 removed

  • tests:+49 added−56 removed
  • other:+52 added−37 removed

3 files+101 added−93 removed

modified:src/flask/helpers.py+49 added-37 removed
487 unmodified lines
488 to send certain files as attachment (HTML for instance). The mimetype489 guessing requires a `filename` or an `attachment_filename` to be490 provided.491492 When passing a file-like object instead of a filename, only binary493 mode is supported (``open(filename, "rb")``, :class:`~io.BytesIO`,494 etc.). Text mode files and :class:`~io.StringIO` will raise a495 :exc:`ValueError`.496497 ETags will also be attached automatically if a `filename` is provided. You498 can turn this off by setting `add_etags=False`.499500 If `conditional=True` and `filename` is provided, this method will try to
2 unmodified lines
503504 Please never pass filenames to this function from user sources;505 you should use :func:`send_from_directory` instead.506502 .. versionadded:: 0.2507 .. versionchanged:: 2.0508 Passing a file-like object that inherits from509 :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather510 than sending an empty file.511504 .. versionadded:: 0.5505 The `add_etags`, `cache_timeout` and `conditional` parameters were506 added. The default behavior is now to attach etags.512 .. versionchanged:: 1.1513 ``filename`` may be a :class:`~os.PathLike` object.514508 .. versionchanged:: 0.7509 mimetype guessing and etag support for file objects was510 deprecated because it was unreliable. Pass a filename if you are511 able to, otherwise attach an etag yourself. This functionality512 will be removed in Flask 1.0515 .. versionchanged:: 1.1516 Passing a :class:`~io.BytesIO` object supports range requests.517514 .. versionchanged:: 0.9515 cache_timeout pulls its default from application config, when None.518 .. versionchanged:: 1.0.3519 Filenames are encoded with ASCII instead of Latin-1 for broader520 compatibility with WSGI servers.521522 .. versionchanged:: 1.0523 UTF-8 filenames, as specified in `RFC 2231`_, are supported.524525 .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4526527 .. versionchanged:: 0.12518 The filename is no longer automatically inferred from file objects. If519 you want to use automatic mimetype and etag support, pass a filepath via520 `filename_or_fp` or `attachment_filename`.528 The filename is no longer automatically inferred from file529 objects. If you want to use automatic MIME and etag support, pass530 a filename via ``filename_or_fp`` or ``attachment_filename``.531532 .. versionchanged:: 0.12523 The `attachment_filename` is preferred over `filename` for MIME-type533 ``attachment_filename`` is preferred over ``filename`` for MIME534 detection.535526 .. versionchanged:: 1.0527 UTF-8 filenames, as specified in `RFC 2231`_, are supported.536 .. versionchanged:: 0.9537 ``cache_timeout`` defaults to538 :meth:`Flask.get_send_file_max_age`.539529 .. _RFC 2231: https://tools.ietf.org/html/rfc2231#section-4540 .. versionchanged:: 0.7541 MIME guessing and etag support for file-like objects was542 deprecated because it was unreliable. Pass a filename if you are543 able to, otherwise attach an etag yourself. This functionality544 will be removed in Flask 1.0.545531 .. versionchanged:: 1.0.3532 Filenames are encoded with ASCII instead of Latin-1 for broader533 compatibility with WSGI servers.546 .. versionadded:: 0.5547 The ``add_etags``, ``cache_timeout`` and ``conditional``548 parameters were added. The default behavior is to add etags.549535 .. versionchanged:: 1.1536 Filename may be a :class:`~os.PathLike` object.550 .. versionadded:: 0.2551538 .. versionadded:: 1.1539 Partial content supports :class:`~io.BytesIO`.540541 :param filename_or_fp: the filename of the file to send.542 This is relative to the :attr:`~Flask.root_path`543 if a relative path is specified.544 Alternatively a file object might be provided in545 which case ``X-Sendfile`` might not work and fall546 back to the traditional method. Make sure that the547 file pointer is positioned at the start of data to548 send before calling :func:`send_file`.552 :param filename_or_fp: The filename of the file to send, relative to553 :attr:`~Flask.root_path` if a relative path is specified.554 Alternatively, a file-like object opened in binary mode. Make555 sure the file pointer is seeked to the start of the data.556 ``X-Sendfile`` will only be used with filenames.557 :param mimetype: the mimetype of the file if provided. If a file path is558 given, auto detection happens as fallback, otherwise an559 error will be raised.560 :param as_attachment: set to ``True`` if you want to send this file with
66 unmodified lines
627628 if current_app.use_x_sendfile and filename:629 if file is not None:630 file.close()631632 headers["X-Sendfile"] = filename633 fsize = os.path.getsize(filename)625 headers["Content-Length"] = fsize634 data = None635 else:636 if file is None:637 file = open(filename, "rb")638 mtime = os.path.getmtime(filename)639 fsize = os.path.getsize(filename)632 headers["Content-Length"] = fsize640 elif isinstance(file, io.BytesIO):641 try:642 fsize = file.getbuffer().nbytes643 except AttributeError:644 # Python 2 doesn't have getbuffer645 fsize = len(file.getvalue())639 headers["Content-Length"] = fsize646 elif isinstance(file, io.TextIOBase):647 raise ValueError("Files must be opened in binary mode or use BytesIO.")648649 data = wrap_file(request.environ, file)650651 if fsize is not None:652 headers["Content-Length"] = fsize653654 rv = current_app.response_class(655 data, mimetype=mimetype, headers=headers, direct_passthrough=True656 )657
508 unmodified lines
modified:tests/test_helpers.py+49 added-56 removed
22 unmodified lines
23from werkzeug.http import parse_options_header2425import flask26from flask import json27from flask._compat import PY228from flask._compat import StringIO29from flask._compat import text_type30from flask.helpers import get_debug_flag31from flask.helpers import get_env
414 unmodified lines
446 except AssertionError:447 assert lines == sorted_by_str448449450class PyStringIO(object):451 def __init__(self, *args, **kwargs):452 self._io = io.BytesIO(*args, **kwargs)453454 def __getattr__(self, name):455 return getattr(self._io, name)456457458class TestSendfile(object):459 def test_send_file_regular(self, app, req_ctx):460 rv = flask.send_file("static/index.html")461 assert rv.direct_passthrough
19 unmodified lines
481482 @app.route("/")483 def index():484 return flask.send_file(476 StringIO("party like it's"),485 io.BytesIO(b"party like it's"),486 last_modified=last_modified,487 mimetype="text/plain",488 )489
1 unmodified line
491 assert rv.last_modified == last_modified492493 def test_send_file_object_without_mimetype(self, app, req_ctx):494 with pytest.raises(ValueError) as excinfo:486 flask.send_file(StringIO("LOL"))495 flask.send_file(io.BytesIO(b"LOL"))496 assert "Unable to infer MIME-type" in str(excinfo.value)497 assert "no filename is available" in str(excinfo.value)498490 flask.send_file(StringIO("LOL"), attachment_filename="filename")499 flask.send_file(io.BytesIO(b"LOL"), attachment_filename="filename")500492 def test_send_file_object(self, app, req_ctx):493 with open(os.path.join(app.root_path, "static/index.html"), mode="rb") as f:494 rv = flask.send_file(f, mimetype="text/html")495 rv.direct_passthrough = False496 with app.open_resource("static/index.html") as f:497 assert rv.data == f.read()498 assert rv.mimetype == "text/html"499 rv.close()500501 @pytest.mark.parametrize(502 "opener",503 [504 lambda app: open(os.path.join(app.static_folder, "index.html"), "rb"),505 lambda app: io.BytesIO(b"Test"),506 pytest.param(507 lambda app: StringIO("Test"),508 marks=pytest.mark.skipif(not PY2, reason="Python 2 only"),509 ),510 lambda app: PyStringIO(b"Test"),511 ],512 )513 @pytest.mark.usefixtures("req_ctx")514 def test_send_file_object(self, app, opener):515 file = opener(app)516 app.use_x_sendfile = True502503 with open(os.path.join(app.root_path, "static/index.html")) as f:504 rv = flask.send_file(f, mimetype="text/html")505 assert rv.mimetype == "text/html"506 assert "x-sendfile" not in rv.headers507 rv.close()508509 app.use_x_sendfile = False510 f = StringIO("Test")511 rv = flask.send_file(f, mimetype="application/octet-stream")517 rv = flask.send_file(file, mimetype="text/plain")518 rv.direct_passthrough = False513 assert rv.data == b"Test"514 assert rv.mimetype == "application/octet-stream"515 rv.close()516517 class PyStringIO(object):518 def __init__(self, *args, **kwargs):519 self._io = StringIO(*args, **kwargs)520521 def __getattr__(self, name):522 return getattr(self._io, name)523524 f = PyStringIO("Test")525 f.name = "test.txt"526 rv = flask.send_file(f, attachment_filename=f.name)527 rv.direct_passthrough = False528 assert rv.data == b"Test"519 assert rv.data520 assert rv.mimetype == "text/plain"521 assert "x-sendfile" not in rv.headers522 rv.close()523532 f = StringIO("Test")533 rv = flask.send_file(f, mimetype="text/plain")534 rv.direct_passthrough = False535 assert rv.data == b"Test"536 assert rv.mimetype == "text/plain"537 rv.close()524 @pytest.mark.parametrize(525 "opener",526 [527 lambda app: io.StringIO(u"Test"),528 pytest.param(529 lambda app: open(os.path.join(app.static_folder, "index.html")),530 marks=pytest.mark.skipif(PY2, reason="Python 3 only"),531 ),532 ],533 )534 @pytest.mark.usefixtures("req_ctx")535 def test_send_file_text_fails(self, app, opener):536 file = opener(app)537539 app.use_x_sendfile = True538 with pytest.raises(ValueError):539 flask.send_file(file, mimetype="text/plain")540541 f = StringIO("Test")542 rv = flask.send_file(f, mimetype="text/html")543 assert "x-sendfile" not in rv.headers544 rv.close()541 file.close()542543 def test_send_file_pathlike(self, app, req_ctx):544 rv = flask.send_file(FakePath("static/index.html"))545 assert rv.direct_passthrough
80 unmodified lines
626 assert rv.status_code == 206627 assert rv.data == b"somethingsomething"[4:16]628 rv.close()629633 @pytest.mark.skipif(634 not callable(getattr(Range, "to_content_range_header", None)),635 reason="not implemented within werkzeug",636 )630 def test_send_file_range_request_xsendfile_invalid(self, app, client):631 # https://github.com/pallets/flask/issues/2526632 app.use_x_sendfile = True633
7 unmodified lines
641642 def test_attachment(self, app, req_ctx):643 app = flask.Flask(__name__)644 with app.test_request_context():652 with open(os.path.join(app.root_path, "static/index.html")) as f:645 with open(os.path.join(app.root_path, "static/index.html"), "rb") as f:646 rv = flask.send_file(647 f, as_attachment=True, attachment_filename="index.html"648 )649 value, options = parse_options_header(rv.headers["Content-Disposition"])650 assert value == "attachment"651 rv.close()652660 with open(os.path.join(app.root_path, "static/index.html")) as f:653 with open(os.path.join(app.root_path, "static/index.html"), "rb") as f:654 rv = flask.send_file(655 f, as_attachment=True, attachment_filename="index.html"656 )657 value, options = parse_options_header(rv.headers["Content-Disposition"])
8 unmodified lines
666 assert options["filename"] == "index.html"667 rv.close()668669 rv = flask.send_file(677 StringIO("Test"),670 io.BytesIO(b"Test"),671 as_attachment=True,672 attachment_filename="index.txt",673 add_etags=False,674 )
369 unmodified lines
modified:CHANGES.rst+3 added
11 unmodified lines
12 :meth:`Config.from_json` is deprecated in favor of this. :pr:`3398`13- The ``flask run`` command will only defer errors on reload. Errors14 present during the initial call will cause the server to exit with15 the traceback immediately. :issue:`3431`16- :func:`send_file` raises a :exc:`ValueError` when passed an17 :mod:`io` object in text mode. Previously, it would respond with18 200 OK and an empty file. :issue:`3358`192021Version 1.1.222-------------
1004 unmodified lines