Merge pull request #4576 from dzcode/dzcode/4567/abort-implementation
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add 'aborter' and 'aborter_class' attrs to 'Flask' object
authored by David Lord · committed by GitHub · parents a25d234, eb5dd9f · Browse files · 5 files·+92 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+92 added−1 removed
- tests:+30 added−0 removed
- other:+62 added−1 removed
Provenance
- Commit
5512a66- Tree
71c5a05- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a25d234- Parent 2
eb5dd9f
5 files changed+92 added−1 removed
modified:src/flask/__init__.py+1 added-1 removed
1 from markupsafe import escape2 from markupsafe import Markup3-from werkzeug.exceptions import abort as abort3 4 from . import json as json5 from .app import Flask as Flask6 from .app import Request as Request9 unmodified lines16 from .globals import current_app as current_app17 from .globals import g as g18 from .globals import request as request19 from .globals import session as session20+from .helpers import abort as abort21 from .helpers import flash as flash22 from .helpers import get_flashed_messages as get_flashed_messages23 from .helpers import get_template_attribute as get_template_attribute24 from .helpers import make_response as make_response21 unmodified linesmodified:src/flask/app.py+30 added
10 unmodified lines11 from types import TracebackType12 13 from werkzeug.datastructures import Headers14 from werkzeug.datastructures import ImmutableDict15+from werkzeug.exceptions import Aborter16 from werkzeug.exceptions import BadRequest17 from werkzeug.exceptions import BadRequestKeyError18 from werkzeug.exceptions import HTTPException19 from werkzeug.exceptions import InternalServerError181 unmodified lines201 #: The class that is used for response objects. See202 #: :class:`~flask.Response` for more information.203 response_class = Response204 205+ #: The class of the object assigned to :attr:`aborter`, created by206+ #: :meth:`create_aborter`. That object is called by207+ #: :func:`flask.abort` to raise HTTP errors, and can be208+ #: called directly as well.209+ #:210+ #: Defaults to :class:`werkzeug.exceptions.Aborter`.211+ #:212+ #: .. versionadded:: 2.2213+ aborter_class = Aborter214+215 #: The class that is used for the Jinja environment.216 #:217 #: .. versionadded:: 0.11218 jinja_environment = Environment212 unmodified lines431 #: exactly like a regular dictionary but supports additional methods432 #: to load a config from files.433 self.config = self.make_config(instance_relative_config)434 435+ #: An instance of :attr:`aborter_class` created by436+ #: :meth:`make_aborter`. This is called by :func:`flask.abort`437+ #: to raise HTTP errors, and can be called directly as well.438+ #:439+ #: .. versionadded:: 2.2440+ self.aborter = self.make_aborter()441+442 #: A list of functions that are called when :meth:`url_for` raises a443 #: :exc:`~werkzeug.routing.BuildError`. Each function registered here444 #: is called with `error`, `endpoint` and `values`. If a function445 #: returns ``None`` or raises a :exc:`BuildError` the next function is199 unmodified lines645 defaults["ENV"] = get_env()646 defaults["DEBUG"] = get_debug_flag()647 return self.config_class(root_path, defaults)648 649+ def make_aborter(self) -> Aborter:650+ """Create the object to assign to :attr:`aborter`. That object651+ is called by :func:`flask.abort` to raise HTTP errors, and can652+ be called directly as well.653+654+ By default, this creates an instance of :attr:`aborter_class`,655+ which defaults to :class:`werkzeug.exceptions.Aborter`.656+657+ .. versionadded:: 2.2658+ """659+ return self.aborter_class()660+661 def auto_find_instance_path(self) -> str:662 """Tries to locate the instance path if it was not provided to the663 constructor of the application class. It will basically calculate664 the path to a folder named ``instance`` next to your main file or1472 unmodified linesmodified:src/flask/helpers.py+27 added
8 unmodified lines9 from functools import update_wrapper10 from threading import RLock11 12 import werkzeug.utils13+from werkzeug.exceptions import abort as _wz_abort14 from werkzeug.routing import BuildError15 from werkzeug.urls import url_quote16 from werkzeug.utils import redirect as _wz_redirect17 6 unmodified lines24 25 if t.TYPE_CHECKING: # pragma: no cover26 from werkzeug.wrappers import Response as BaseResponse27 from .wrappers import Response28+ import typing_extensions as te29 30 31 def get_env() -> str:32 """Get the environment the app is running in, indicated by the332 unmodified lines365 366 return _wz_redirect(location, code=code, Response=Response)367 368 369+def abort( # type: ignore[misc]370+ code: t.Union[int, "BaseResponse"], *args: t.Any, **kwargs: t.Any371+) -> "te.NoReturn":372+ """Raise an :exc:`~werkzeug.exceptions.HTTPException` for the given373+ status code.374+375+ If :data:`~flask.current_app` is available, it will call its376+ :attr:`~flask.Flask.aborter` object, otherwise it will use377+ :func:`werkzeug.exceptions.abort`.378+379+ :param code: The status code for the exception, which must be380+ registered in ``app.aborter``.381+ :param args: Passed to the exception.382+ :param kwargs: Passed to the exception.383+384+ .. versionadded:: 2.2385+ Calls ``current_app.aborter`` if available instead of always386+ using Werkzeug's default ``abort``.387+ """388+ if current_app:389+ current_app.aborter(code, *args, **kwargs)390+391+ _wz_abort(code, *args, **kwargs)392+393+394 def get_template_attribute(template_name: str, attribute: str) -> t.Any:395 """Loads a macro (or variable) a template exports. This can be used to396 invoke a macro from within Python code. If you for example have a397 template named :file:`_cider.html` with the following contents:444 unmodified linesmodified:tests/test_helpers.py+30 added
1 import io2 import os3 4 import pytest5+import werkzeug.exceptions6 7 import flask8 from flask.helpers import get_debug_flag9 from flask.helpers import get_env164 unmodified lines174 with app.app_context(), pytest.raises(ValueError):175 flask.redirect("other")176 177 178+def test_abort_no_app():179+ with pytest.raises(werkzeug.exceptions.Unauthorized):180+ flask.abort(401)181+182+ with pytest.raises(LookupError):183+ flask.abort(900)184+185+186+def test_app_aborter_class():187+ class MyAborter(werkzeug.exceptions.Aborter):188+ pass189+190+ class MyFlask(flask.Flask):191+ aborter_class = MyAborter192+193+ app = MyFlask(__name__)194+ assert isinstance(app.aborter, MyAborter)195+196+197+def test_abort_with_app(app):198+ class My900Error(werkzeug.exceptions.HTTPException):199+ code = 900200+201+ app.aborter.mapping[900] = My900Error202+203+ with app.app_context(), pytest.raises(My900Error):204+ flask.abort(900)205+206+207 class TestNoImports:208 """Test Flasks are created without import.209 210 Avoiding ``__import__`` helps create Flask instances where there are errors149 unmodified linesmodified:CHANGES.rst+4 added
3 unmodified lines4 -------------5 6 Unreleased7 8+- Add ``aborter_class`` and ``aborter`` attributes to the Flask app9+ object. ``flask.abort`` will call ``app.aborter``. This makes it10+ possible for an app to override how aborts work, including custom11+ status codes. :issue:`4567`12 - Add an ``app.redirect`` method, which ``flask.redirect`` will call.13 This makes it possible for an app to override how redirects work.14 :issue:`4569`15 - Refactor ``register_error_handler`` to consolidate error checking.1285 unmodified lines