Merge pull request #3894 from pallets/update-werkzeug
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Update for recent changes in Pallets libraries
authored by David Lord · committed by GitHub · parents d887d32, 81ba6c2 · Browse files · 11 files·+59 added−79 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+59 added−79 removed
- other:+59 added−79 removed
Provenance
- Commit
9f7ac04- Tree
d75e8a1- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d887d32- Parent 2
81ba6c2
11 files changed+59 added−79 removed
modified:docs/tutorial/tests.rst+1 added-1 removed
300 unmodified lines301 302 :attr:`~Response.data` contains the body of the response as bytes. If303 you expect a certain value to render on the page, check that it's in304 ``data``. Bytes must be compared to bytes. If you want to compare text,305-use :meth:`get_data(as_text=True) <werkzeug.wrappers.BaseResponse.get_data>`305+use :meth:`get_data(as_text=True) <werkzeug.wrappers.Response.get_data>`306 instead.307 308 ``pytest.mark.parametrize`` tells Pytest to run the same test function309 with different arguments. You use it here to test different invalid252 unmodified linesmodified:docs/api.rst+6 added-17 removed
25 unmodified lines26 Incoming Request Data27 ---------------------28 29 .. autoclass:: Request30- :members:31- :inherited-members:32- :exclude-members: json_module30+ :members:31+ :inherited-members:32+ :exclude-members: json_module33 34 .. attribute:: request35 36 To access incoming request data, you can use the global `request`10 unmodified lines47 Response Objects48 ----------------49 50 .. autoclass:: flask.Response51- :members: set_cookie, max_cookie_size, data, mimetype, is_json, get_json51+ :members:52+ :inherited-members:53+ :exclude-members: json_module54 53- .. attribute:: headers54-55- A :class:`~werkzeug.datastructures.Headers` object representing the response headers.56-57- .. attribute:: status58-59- A string with a response status.60-61- .. attribute:: status_code62-63- The response status as integer.64-65-55 Sessions56 --------57 58 If you have set :attr:`Flask.secret_key` (or configured it from702 unmodified linesmodified:docs/errorhandling.rst+4 added-18 removed
247 unmodified lines248 be passed an instance of ``InternalServerError``, not the original249 unhandled error.250 251 The original error is available as ``e.original_exception``.252-Until Werkzeug 1.0.0, this attribute will only exist during unhandled253-errors, use ``getattr`` to get access it for compatibility.252 255-.. code-block:: python253+An error handler for "500 Internal Server Error" will be passed uncaught254+exceptions in addition to explicit 500 errors. In debug mode, a handler255+for "500 Internal Server Error" will not be used. Instead, the256+interactive debugger will be shown.257 257- @app.errorhandler(InternalServerError)258- def handle_500(e):259- original = getattr(e, "original_exception", None)258 261- if original is None:262- # direct 500 error, such as abort(500)263- return render_template("500.html"), 500264-265- # wrapped unhandled error266- return render_template("500_unhandled.html", e=original), 500267-268-An error handler for "500 Internal Server Error" will be passed uncaught exceptions in269-addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.270-Instead, the interactive debugger will be shown.271-272-259 Custom Error Pages260 ------------------261 262 Sometimes when building a Flask application, you might want to raise a262 unmodified linesmodified:docs/testing.rst+1 added-1 removed
117 unmodified lines118 119 By using ``client.get`` we can send an HTTP ``GET`` request to the120 application with the given path. The return value will be a121 :class:`~flask.Flask.response_class` object. We can now use the122-:attr:`~werkzeug.wrappers.BaseResponse.data` attribute to inspect122+:attr:`~werkzeug.wrappers.Response.data` attribute to inspect123 the return value (as string) from the application.124 In this case, we ensure that ``'No entries here so far'``125 is part of the output.126 336 unmodified linesmodified:src/flask/__main__.py+1 added-1 removed
1 from .cli import main2 3-main(as_module=True)3+main()modified:src/flask/app.py+7 added-17 removed
14 unmodified lines15 from werkzeug.routing import Map16 from werkzeug.routing import RequestRedirect17 from werkzeug.routing import RoutingException18 from werkzeug.routing import Rule19-from werkzeug.wrappers import BaseResponse19+from werkzeug.wrappers import Response as BaseResponse20 21 from . import cli22 from . import json23 from .config import Config253 unmodified lines277 #: .. versionchanged:: 1.1.0278 #: This is a ``dict`` instead of an ``ImmutableDict`` to allow279 #: easier configuration.280 #:281- jinja_options = {"extensions": ["jinja2.ext.autoescape", "jinja2.ext.with_"]}281+ jinja_options = {}282 283 #: Default configuration parameters.284 default_config = ImmutableDict(285 {1099 unmodified lines1385 message.1386 1387 .. versionadded:: 0.71388 """1389- if isinstance(e, BadRequestKeyError):1390- if self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]:1391- e.show_exception = True1389+ if isinstance(e, BadRequestKeyError) and (1390+ self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1391+ ):1392+ e.show_exception = True1393 1393- # Werkzeug < 0.15 doesn't add the KeyError to the 4001394- # message, add it in manually.1395- # TODO: clean up once Werkzeug >= 0.15.5 is required1396- if e.args[0] not in e.get_description():1397- e.description = f"KeyError: {e.args[0]!r}"1398- elif not hasattr(BadRequestKeyError, "show_exception"):1399- e.args = ()1400-1394 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1395 return self.handle_http_exception(e)1396 1397 handler = self._find_error_handler(e)48 unmodified lines1446 1447 raise e1448 1449 self.log_exception(exc_info)1457- server_error = InternalServerError()1458- # TODO: pass as param when Werkzeug>=1.0.0 is required1459- # TODO: also remove note about this from docstring and docs1460- server_error.original_exception = e1450+ server_error = InternalServerError(original_exception=e)1451 handler = self._find_error_handler(server_error)1452 1453 if handler is not None:1454 server_error = handler(server_error)578 unmodified linesmodified:src/flask/cli.py+3 added-3 removed
951 unmodified lines952 )953 )954 955 956-def main(as_module=False):956+def main():957 # TODO omit sys.argv once https://github.com/pallets/click/issues/536 is fixed958- cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)958+ cli.main(args=sys.argv[1:])959 960 961 if __name__ == "__main__":962- main(as_module=True)962+ main()modified:src/flask/helpers.py+21 added-3 removed
437 unmodified lines438 439 def _prepare_send_file_kwargs(440 download_name=None,441 attachment_filename=None,442+ etag=None,443+ add_etags=None,444 max_age=None,445 cache_timeout=None,446 **kwargs,447 ):14 unmodified lines462 stacklevel=3,463 )464 max_age = cache_timeout465 466+ if add_etags is not None:467+ warnings.warn(468+ "The 'add_etags' parameter has been renamed to 'etag'. The old name will be"469+ " removed in Flask 2.1.",470+ DeprecationWarning,471+ stacklevel=3,472+ )473+ etag = add_etags474+475 if max_age is None:476 max_age = current_app.get_send_file_max_age477 478 kwargs.update(479 environ=request.environ,480 download_name=download_name,481+ etag=etag,482 max_age=max_age,483 use_x_sendfile=current_app.use_x_sendfile,484 response_class=current_app.response_class,485 _root_path=current_app.root_path,7 unmodified lines493 as_attachment=False,494 download_name=None,495 attachment_filename=None,496 conditional=True,485- add_etags=True,497+ etag=True,498+ add_etags=None,499 last_modified=None,500 max_age=None,501 cache_timeout=None,502 ):27 unmodified lines530 :param download_name: The default name browsers will use when saving531 the file. Defaults to the passed file name.532 :param conditional: Enable conditional and range responses based on533 request headers. Requires passing a file path and ``environ``.521- :param add_etags: Calculate an ETag for the file. Requires passing a522- file path.534+ :param etag: Calculate an ETag for the file, which requires passing535+ a file path. Can also be a string to use instead.536 :param last_modified: The last modified time to send for the file,537 in seconds. If not provided, it will try to detect it from the538 file path.539 :param max_age: How long the client should cache the file, in9 unmodified lines549 ``max_age`` replaces the ``cache_timeout`` parameter.550 ``conditional`` is enabled and ``max_age`` is not set by551 default.552 553+ .. versionchanged:: 2.0.0554+ ``etag`` replaces the ``add_etags`` parameter. It can be a555+ string to use instead of generating one.556+557 .. versionchanged:: 2.0558 Passing a file-like object that inherits from559 :class:`~io.TextIOBase` will raise a :exc:`ValueError` rather560 than sending an empty file.48 unmodified lines609 as_attachment=as_attachment,610 download_name=download_name,611 attachment_filename=attachment_filename,612 conditional=conditional,613+ etag=etag,614 add_etags=add_etags,615 last_modified=last_modified,616 max_age=max_age,617 cache_timeout=cache_timeout,417 unmodified linesmodified:src/flask/testing.py+1 added-1 removed
3 unmodified lines4 import werkzeug.test5 from click.testing import CliRunner6 from werkzeug.test import Client7 from werkzeug.urls import url_parse8-from werkzeug.wrappers import BaseRequest8+from werkzeug.wrappers import Request as BaseRequest9 10 from . import _request_ctx_stack11 from .cli import ScriptInfo12 from .json import dumps as json_dumps249 unmodified linesmodified:src/flask/wrappers.py+12 added-16 removed
1 from werkzeug.exceptions import BadRequest2 from werkzeug.wrappers import Request as RequestBase3 from werkzeug.wrappers import Response as ResponseBase4-from werkzeug.wrappers.json import JSONMixin as _JSONMixin4 5 from . import json6 from .globals import current_app7 8 10-class JSONMixin(_JSONMixin):11- json_module = json12-13- def on_json_loading_failed(self, e):14- if current_app and current_app.debug:15- raise BadRequest(f"Failed to decode JSON object: {e}")16-17- raise BadRequest()18-19-20-class Request(RequestBase, JSONMixin):9+class Request(RequestBase):10 """The request object used by default in Flask. Remembers the11 matched endpoint and view arguments.12 13 It is what ends up as :class:`~flask.request`. If you want to replace4 unmodified lines18 provides all of the attributes Werkzeug defines plus a few Flask19 specific ones.20 """21 22+ json_module = json23+24 #: The internal URL rule that matched the request. This can be25 #: useful to inspect which methods are allowed for the URL from26 #: a before/after handler (``request.url_rule.methods``) etc.27 #: Though if the request's method was invalid for the URL rule,51 unmodified lines79 from .debughelpers import attach_enctype_error_multidict80 81 attach_enctype_error_multidict(self)82 83+ def on_json_loading_failed(self, e):84+ if current_app and current_app.debug:85+ raise BadRequest(f"Failed to decode JSON object: {e}")86 87+ raise BadRequest()88+89+93-class Response(JSONMixin, ResponseBase):90+class Response(ResponseBase):91 """The response object that is used by default in Flask. Works like the92 response object from Werkzeug but is set to have an HTML mimetype by93 default. Quite often you don't have to create this object yourself because94 :meth:`~flask.Flask.make_response` will take care of that for you.11 unmodified lines106 """107 108 default_mimetype = "text/html"109 113- def _get_data_for_json(self, cache):114- return self.get_data()110+ json_module = json111 112 @property113 def max_cookie_size(self):114 """Read-only view of the :data:`MAX_COOKIE_SIZE` config key.115 120- See :attr:`~werkzeug.wrappers.BaseResponse.max_cookie_size` in116+ See :attr:`~werkzeug.wrappers.Response.max_cookie_size` in117 Werkzeug's docs.118 """119 if current_app:120 return current_app.config["MAX_COOKIE_SIZE"]3 unmodified linesmodified:CHANGES.rst+2 added-1 removed
47 unmodified lines48 - ``send_file`` and ``send_from_directory`` are wrappers around the49 implementations in ``werkzeug.utils``. :pr:`3828`50 - Some ``send_file`` parameters have been renamed, the old names are51 deprecated. ``attachment_filename`` is renamed to ``download_name``.52- ``cache_timeout`` is renamed to ``max_age``. :pr:`3828`52+ ``cache_timeout`` is renamed to ``max_age``. ``add_etags`` is53+ renamed to ``etag``. :pr:`3828, 3883`54 - ``send_file`` passes ``download_name`` even if55 ``as_attachment=False`` by using ``Content-Disposition: inline``.56 :pr:`3828`57 - ``send_file`` sets ``conditional=True`` and ``max_age=None`` by1020 unmodified lines