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
Provenance
- Commit
4d37aca- Tree
9ebe908- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
f7d50d4- Parent 2
25de45c
4 files changed+62 added−5 removed
modified:flask/_compat.py+9 added
95 unmodified lines96 except TypeError:97 BROKEN_PYPY_CTXMGR_EXIT = True98 except AssertionError:99 pass100+101+102+try:103+ from os import fspath104+except 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 pathmodified:flask/helpers.py+10 added-1 removed
31 unmodified lines32 33 from .signals import message_flashed34 from .globals import session, _request_ctx_stack, _app_ctx_stack, \35 current_app, request36-from ._compat import string_types, text_type, PY236+from ._compat import string_types, text_type, PY2, fspath37 38 # sentinel39 _missing = object()40 468 unmodified lines509 .. versionchanged:: 1.0.3510 Filenames are encoded with ASCII instead of Latin-1 for broader511 compatibility with WSGI servers.512 513+ .. versionchanged:: 1.1514+ Filenames may be a `PathLike` object.515+516 :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 in20 unmodified lines540 If a file was passed, this overrides its mtime.541 """542 mtime = None543 fsize = None544+545+ if hasattr(filename_or_fp, '__fspath__'):546+ filename_or_fp = fspath(filename_or_fp)547+548 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 lines711 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 linesmodified:tests/test_helpers.py+36 added
34 unmodified lines35 except LookupError:36 return False37 38 39+class FakePath(object):40+ """Fake object to represent a ``PathLike object``.41+42+ 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 = path47+48+ def __fspath__(self):49+ return self.path50+51+52 class FixedOffset(datetime.tzinfo):53 """Fixed offset in hours east from UTC.54 55 This is a slight adaptation of the ``FixedOffset`` example found in483 unmodified lines539 rv = flask.send_file(f, mimetype='text/html')540 assert 'x-sendfile' not in rv.headers541 rv.close()542 543+ 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()551+552 @pytest.mark.skipif(553 not callable(getattr(Range, 'to_content_range_header', None)),554 reason="not implemented within werkzeug"555 )146 unmodified lines702 cc = parse_cache_control_header(rv.headers['Cache-Control'])703 assert cc.max_age == 3600704 rv.close()705 706+ # 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()711+712 class StaticFileApp(flask.Flask):713 def get_send_file_max_age(self, filename):714 return 10715 17 unmodified lines733 rv.direct_passthrough = False734 assert rv.data.strip() == b'Hello Subdomain'735 rv.close()736 737+ 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()744+745 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 linesmodified:CHANGES.rst+7 added-4 removed
8 unmodified lines9 10 Unreleased11 12 - :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`_)20 21 .. _#2935: https://github.com/pallets/flask/issues/293522 .. _#2994: https://github.com/pallets/flask/pull/299423+.. _#3059: https://github.com/pallets/flask/pull/305924 25 26 Version 1.0.327 -------------329 unmodified lines357 - 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- 361+362 .. _#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/200612 unmodified lines378 379 Bugfix release, released on June 7th 2016.380 381 - Fixed a bug that prevented ``FLASK_APP=foobar/__init__.py`` from working. (`#1872`_)379- 382+383 .. _#1872: https://github.com/pallets/flask/pull/1872384 385 Version 0.11386 ------------71 unmodified lines458 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- 462+463 .. _#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/1515487 unmodified lines