Skip to content
Myr

Merge pull request #3059 from mattrobenolt/fspath

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

Add support for PathLike objects in static file helpers

authored by David Lord · committed by GitHub · parents f7d50d4, 25de45c · Browse files · 4 files+62 added−5 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+62 added−5 removed

  • tests:+36 added−0 removed
  • other:+26 added−5 removed

4 files+62 added−5 removed

modified:flask/_compat.py+9 added
95 unmodified lines
96 except TypeError:97 BROKEN_PYPY_CTXMGR_EXIT = True98 except AssertionError:99 pass100101102try:103 from os import fspath104except ImportError:105 # Backwards compatibility as proposed in PEP 0519:106 # https://www.python.org/dev/peps/pep-0519/#backwards-compatibility107 def fspath(path):108 return path.__fspath__() if hasattr(path, '__fspath__') else path
modified:flask/helpers.py+10 added-1 removed
31 unmodified lines
3233from .signals import message_flashed34from .globals import session, _request_ctx_stack, _app_ctx_stack, \35 current_app, request36from ._compat import string_types, text_type, PY236from ._compat import string_types, text_type, PY2, fspath3738# sentinel39_missing = object()40
468 unmodified lines
509 .. versionchanged:: 1.0.3510 Filenames are encoded with ASCII instead of Latin-1 for broader511 compatibility with WSGI servers.512513 .. versionchanged:: 1.1514 Filenames may be a `PathLike` object.515516 :param filename_or_fp: the filename of the file to send.517 This is relative to the :attr:`~Flask.root_path`518 if a relative path is specified.519 Alternatively a file object might be provided in
20 unmodified lines
540 If a file was passed, this overrides its mtime.541 """542 mtime = None543 fsize = None544545 if hasattr(filename_or_fp, '__fspath__'):546 filename_or_fp = fspath(filename_or_fp)547548 if isinstance(filename_or_fp, string_types):549 filename = filename_or_fp550 if not os.path.isabs(filename):551 filename = os.path.join(current_app.root_path, filename)
159 unmodified lines
711 download.712 :param options: optional keyword arguments that are directly713 forwarded to :func:`send_file`.714 """715 filename = fspath(filename)716 directory = fspath(directory)717 filename = safe_join(directory, filename)718 if not os.path.isabs(filename):719 filename = os.path.join(current_app.root_path, filename)720 try:
337 unmodified lines
modified:tests/test_helpers.py+36 added
34 unmodified lines
35 except LookupError:36 return False373839class FakePath(object):40 """Fake object to represent a ``PathLike object``.4142 This represents a ``pathlib.Path`` object in python 3.43 See: https://www.python.org/dev/peps/pep-0519/44 """45 def __init__(self, path):46 self.path = path4748 def __fspath__(self):49 return self.path505152class FixedOffset(datetime.tzinfo):53 """Fixed offset in hours east from UTC.5455 This is a slight adaptation of the ``FixedOffset`` example found in
483 unmodified lines
539 rv = flask.send_file(f, mimetype='text/html')540 assert 'x-sendfile' not in rv.headers541 rv.close()542543 def test_send_file_pathlike(self, app, req_ctx):544 rv = flask.send_file(FakePath('static/index.html'))545 assert rv.direct_passthrough546 assert rv.mimetype == 'text/html'547 with app.open_resource('static/index.html') as f:548 rv.direct_passthrough = False549 assert rv.data == f.read()550 rv.close()551552 @pytest.mark.skipif(553 not callable(getattr(Range, 'to_content_range_header', None)),554 reason="not implemented within werkzeug"555 )
146 unmodified lines
702 cc = parse_cache_control_header(rv.headers['Cache-Control'])703 assert cc.max_age == 3600704 rv.close()705706 # Test with static file handler.707 rv = app.send_static_file(FakePath('index.html'))708 cc = parse_cache_control_header(rv.headers['Cache-Control'])709 assert cc.max_age == 3600710 rv.close()711712 class StaticFileApp(flask.Flask):713 def get_send_file_max_age(self, filename):714 return 10715
17 unmodified lines
733 rv.direct_passthrough = False734 assert rv.data.strip() == b'Hello Subdomain'735 rv.close()736737 def test_send_from_directory_pathlike(self, app, req_ctx):738 app.root_path = os.path.join(os.path.dirname(__file__),739 'test_apps', 'subdomaintestmodule')740 rv = flask.send_from_directory(FakePath('static'), FakePath('hello.txt'))741 rv.direct_passthrough = False742 assert rv.data.strip() == b'Hello Subdomain'743 rv.close()744745 def test_send_from_directory_bad_request(self, app, req_ctx):746 app.root_path = os.path.join(os.path.dirname(__file__),747 'test_apps', 'subdomaintestmodule')748
242 unmodified lines
modified:CHANGES.rst+7 added-4 removed
8 unmodified lines
910Unreleased1112- :meth:`flask.RequestContext.copy` includes the current session13 object in the request context copy. This prevents ``flask.session`` 13 object in the request context copy. This prevents ``flask.session``14 pointing to an out-of-date object. (`#2935`)15- Using built-in RequestContext, unprintable Unicode characters in Host16 header will result in a HTTP 400 response and not HTTP 500 as previously.17 (`#2994`)18- :func:`send_file` supports ``PathLike`` objects as describe in19 PEP 0519, to support ``pathlib`` in Python 3. (`#3059`_)2021.. _#2935: https://github.com/pallets/flask/issues/293522.. _#2994: https://github.com/pallets/flask/pull/299423.. _#3059: https://github.com/pallets/flask/pull/3059242526Version 1.0.327-------------
329 unmodified lines
357- Disable logger propagation by default for the app logger.358- Add support for range requests in ``send_file``.359- ``app.test_client`` includes preset default environment, which can now be360 directly set, instead of per ``client.get``.358 361362.. _#1849: https://github.com/pallets/flask/pull/1849363.. _#1988: https://github.com/pallets/flask/pull/1988364.. _#1730: https://github.com/pallets/flask/pull/1730365.. _#2006: https://github.com/pallets/flask/pull/2006
12 unmodified lines
378379Bugfix release, released on June 7th 2016.380381- Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. (`#1872`_)379 382383.. _#1872: https://github.com/pallets/flask/pull/1872384385Version 0.11386------------
71 unmodified lines
458 the server OS (`#1763`_).459- Added the ``JSONIFY_MIMETYPE`` configuration variable (`#1728`_).460- Exceptions during teardown handling will no longer leave bad application461 contexts lingering around.459 462463.. _#1326: https://github.com/pallets/flask/pull/1326464.. _#1393: https://github.com/pallets/flask/pull/1393465.. _#1422: https://github.com/pallets/flask/pull/1422466.. _#1515: https://github.com/pallets/flask/pull/1515
487 unmodified lines