Skip to content
Myr

Merge pull request #4580 from ionesu/move_url_for_to_the_flask_app_object

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

Move url_for to the Flask app object

authored by David Lord · committed by GitHub · parents fac6303, 39f9363 · Browse files · 3 files+200 added−158 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+200 added−158 removed

  • tests:+8 added−4 removed
  • other:+192 added−154 removed

3 files+200 added−158 removed

modified:src/flask/app.py+147 added-9 removed
21 unmodified lines
22from werkzeug.routing import MapAdapter23from werkzeug.routing import RequestRedirect24from werkzeug.routing import RoutingException25from werkzeug.routing import Rule26from werkzeug.urls import url_quote27from werkzeug.utils import redirect as _wz_redirect28from werkzeug.wrappers import Response as BaseResponse2930from . import cli
2 unmodified lines
33from .config import ConfigAttribute34from .ctx import _AppCtxGlobals35from .ctx import AppContext36from .ctx import RequestContext37from .globals import _app_ctx_stack38from .globals import _request_ctx_stack39from .globals import g40from .globals import request41from .globals import session
398 unmodified lines
440 #:441 #: .. versionadded:: 2.2442 self.aborter = self.make_aborter()443442 #: 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 is446 #: tried.444 #: A list of functions that are called by445 #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a446 #: :exc:`~werkzeug.routing.BuildError`. Each function is called447 #: with ``error``, ``endpoint`` and ``values``. If a function448 #: returns ``None`` or raises a ``BuildError``, it is skipped.449 #: Otherwise, its return value is returned by ``url_for``.450 #:451 #: .. versionadded:: 0.9452 self.url_build_error_handlers: t.List[450 t.Callable[[Exception, str, dict], str]453 t.Callable[[Exception, str, t.Dict[str, t.Any]], str]454 ] = []455456 #: A list of functions that will be called at the beginning of the457 #: first request to this instance. To register a function, use the
1205 unmodified lines
1663 ) from None16641665 return asgiref_async_to_sync(func)16661667 def url_for(1668 self,1669 endpoint: str,1670 *,1671 _anchor: t.Optional[str] = None,1672 _method: t.Optional[str] = None,1673 _scheme: t.Optional[str] = None,1674 _external: t.Optional[bool] = None,1675 **values: t.Any,1676 ) -> str:1677 """Generate a URL to the given endpoint with the given values.16781679 This is called by :func:`flask.url_for`, and can be called1680 directly as well.16811682 An *endpoint* is the name of a URL rule, usually added with1683 :meth:`@app.route() <route>`, and usually the same name as the1684 view function. A route defined in a :class:`~flask.Blueprint`1685 will prepend the blueprint's name separated by a ``.`` to the1686 endpoint.16871688 In some cases, such as email messages, you want URLs to include1689 the scheme and domain, like ``https://example.com/hello``. When1690 not in an active request, URLs will be external by default, but1691 this requires setting :data:`SERVER_NAME` so Flask knows what1692 domain to use. :data:`APPLICATION_ROOT` and1693 :data:`PREFERRED_URL_SCHEME` should also be configured as1694 needed. This config is only used when not in an active request.16951696 Functions can be decorated with :meth:`url_defaults` to modify1697 keyword arguments before the URL is built.16981699 If building fails for some reason, such as an unknown endpoint1700 or incorrect values, the app's :meth:`handle_url_build_error`1701 method is called. If that returns a string, that is returned,1702 otherwise a :exc:`~werkzeug.routing.BuildError` is raised.17031704 :param endpoint: The endpoint name associated with the URL to1705 generate. If this starts with a ``.``, the current blueprint1706 name (if any) will be used.1707 :param _anchor: If given, append this as ``#anchor`` to the URL.1708 :param _method: If given, generate the URL associated with this1709 method for the endpoint.1710 :param _scheme: If given, the URL will have this scheme if it1711 is external.1712 :param _external: If given, prefer the URL to be internal1713 (False) or require it to be external (True). External URLs1714 include the scheme and domain. When not in an active1715 request, URLs are external by default.1716 :param values: Values to use for the variable parts of the URL1717 rule. Unknown keys are appended as query string arguments,1718 like ``?a=b&c=d``.17191720 .. versionadded:: 2.21721 Moved from ``flask.url_for``, which calls this method.1722 """1723 req_ctx = _request_ctx_stack.top17241725 if req_ctx is not None:1726 url_adapter = req_ctx.url_adapter1727 blueprint_name = req_ctx.request.blueprint17281729 # If the endpoint starts with "." and the request matches a1730 # blueprint, the endpoint is relative to the blueprint.1731 if endpoint[:1] == ".":1732 if blueprint_name is not None:1733 endpoint = f"{blueprint_name}{endpoint}"1734 else:1735 endpoint = endpoint[1:]17361737 # When in a request, generate a URL without scheme and1738 # domain by default, unless a scheme is given.1739 if _external is None:1740 _external = _scheme is not None1741 else:1742 app_ctx = _app_ctx_stack.top17431744 # If called by helpers.url_for, an app context is active,1745 # use its url_adapter. Otherwise, app.url_for was called1746 # directly, build an adapter.1747 if app_ctx is not None:1748 url_adapter = app_ctx.url_adapter1749 else:1750 url_adapter = self.create_url_adapter(None)17511752 if url_adapter is None:1753 raise RuntimeError(1754 "Unable to build URLs outside an active request"1755 " without 'SERVER_NAME' configured. Also configure"1756 " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"1757 " needed."1758 )17591760 # When outside a request, generate a URL with scheme and1761 # domain by default.1762 if _external is None:1763 _external = True17641765 # It is an error to set _scheme when _external=False, in order1766 # to avoid accidental insecure URLs.1767 if _scheme is not None and not _external:1768 raise ValueError("When specifying '_scheme', '_external' must be True.")17691770 self.inject_url_defaults(endpoint, values)17711772 try:1773 rv = url_adapter.build(1774 endpoint,1775 values,1776 method=_method,1777 url_scheme=_scheme,1778 force_external=_external,1779 )1780 except BuildError as error:1781 values.update(1782 _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external1783 )1784 return self.handle_url_build_error(error, endpoint, values)17851786 if _anchor is not None:1787 rv = f"{rv}#{url_quote(_anchor)}"17881789 return rv17901791 def redirect(self, location: str, code: int = 302) -> BaseResponse:1792 """Create a redirect response object.17931794 This is called by :func:`flask.redirect`, and can be called
191 unmodified lines
1986 for func in self.url_default_functions[name]:1987 func(endpoint, values)19881989 def handle_url_build_error(1863 self, error: Exception, endpoint: str, values: dict1990 self, error: BuildError, endpoint: str, values: t.Dict[str, t.Any]1991 ) -> str:1865 """Handle :class:`~werkzeug.routing.BuildError` on1866 :meth:`url_for`.1992 """Called by :meth:`.url_for` if a1993 :exc:`~werkzeug.routing.BuildError` was raised. If this returns1994 a value, it will be returned by ``url_for``, otherwise the error1995 will be re-raised.19961997 Each function in :attr:`url_build_error_handlers` is called with1998 ``error``, ``endpoint`` and ``values``. If a function returns1999 ``None`` or raises a ``BuildError``, it is skipped. Otherwise,2000 its return value is returned by ``url_for``.20012002 :param error: The active ``BuildError`` being handled.2003 :param endpoint: The endpoint being built.2004 :param values: The keyword arguments passed to ``url_for``.2005 """2006 for handler in self.url_build_error_handlers:2007 try:2008 rv = handler(error, endpoint, values)
269 unmodified lines
modified:src/flask/helpers.py+45 added-145 removed
9 unmodified lines
10from threading import RLock1112import werkzeug.utils13from werkzeug.exceptions import abort as _wz_abort14from werkzeug.routing import BuildError15from werkzeug.urls import url_quote14from werkzeug.utils import redirect as _wz_redirect1518from .globals import _app_ctx_stack16from .globals import _request_ctx_stack17from .globals import current_app18from .globals import request19from .globals import session
169 unmodified lines
189 args = args[0]190 return current_app.make_response(args) # type: ignore191192196def url_for(endpoint: str, **values: t.Any) -> str:197 """Generates a URL to the given endpoint with the method provided.193def url_for(194 endpoint: str,195 *,196 _anchor: t.Optional[str] = None,197 _method: t.Optional[str] = None,198 _scheme: t.Optional[str] = None,199 _external: t.Optional[bool] = None,200 **values: t.Any,201) -> str:202 """Generate a URL to the given endpoint with the given values.203199 Variable arguments that are unknown to the target endpoint are appended200 to the generated URL as query arguments. If the value of a query argument201 is ``None``, the whole pair is skipped. In case blueprints are active202 you can shortcut references to the same blueprint by prefixing the203 local endpoint with a dot (``.``).204 This requires an active request or application context, and calls205 :meth:`current_app.url_for() <flask.Flask.url_for>`. See that method206 for full documentation.207205 This will reference the index function local to the current blueprint::208 :param endpoint: The endpoint name associated with the URL to209 generate. If this starts with a ``.``, the current blueprint210 name (if any) will be used.211 :param _anchor: If given, append this as ``#anchor`` to the URL.212 :param _method: If given, generate the URL associated with this213 method for the endpoint.214 :param _scheme: If given, the URL will have this scheme if it is215 external.216 :param _external: If given, prefer the URL to be internal (False) or217 require it to be external (True). External URLs include the218 scheme and domain. When not in an active request, URLs are219 external by default.220 :param values: Values to use for the variable parts of the URL rule.221 Unknown keys are appended as query string arguments, like222 ``?a=b&c=d``.223207 url_for('.index')224 .. versionchanged:: 2.2225 Calls ``current_app.url_for``, allowing an app to override the226 behavior.227209 See :ref:`url-building`.228 .. versionchanged:: 0.10229 The ``_scheme`` parameter was added.230211 Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when212 generating URLs outside of a request context.231 .. versionchanged:: 0.9232 The ``_anchor`` and ``_method`` parameters were added.233214 To integrate applications, :class:`Flask` has a hook to intercept URL build215 errors through :attr:`Flask.url_build_error_handlers`. The `url_for`216 function results in a :exc:`~werkzeug.routing.BuildError` when the current217 app does not have a URL for the given endpoint and values. When it does, the218 :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if219 it is not ``None``, which can return a string to use as the result of220 `url_for` (instead of `url_for`'s default to raise the221 :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.222 An example::223224 def external_url_handler(error, endpoint, values):225 "Looks up an external URL when `url_for` cannot build a URL."226 # This is an example of hooking the build_error_handler.227 # Here, lookup_url is some utility function you've built228 # which looks up the endpoint in some external URL registry.229 url = lookup_url(endpoint, **values)230 if url is None:231 # External lookup did not have a URL.232 # Re-raise the BuildError, in context of original traceback.233 exc_type, exc_value, tb = sys.exc_info()234 if exc_value is error:235 raise exc_type(exc_value).with_traceback(tb)236 else:237 raise error238 # url_for will use this result, instead of raising BuildError.239 return url240241 app.url_build_error_handlers.append(external_url_handler)242243 Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and244 `endpoint` and `values` are the arguments passed into `url_for`. Note245 that this is for building URLs outside the current application, and not for246 handling 404 NotFound errors.247248 .. versionadded:: 0.10249 The `_scheme` parameter was added.250251 .. versionadded:: 0.9252 The `_anchor` and `_method` parameters were added.253254 .. versionadded:: 0.9255 Calls :meth:`Flask.handle_build_error` on256 :exc:`~werkzeug.routing.BuildError`.257258 :param endpoint: the endpoint of the URL (name of the function)259 :param values: the variable arguments of the URL rule260 :param _external: if set to ``True``, an absolute URL is generated. Server261 address can be changed via ``SERVER_NAME`` configuration variable which262 falls back to the `Host` header, then to the IP and port of the request.263 :param _scheme: a string specifying the desired URL scheme. The `_external`264 parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default265 behavior uses the same scheme as the current request, or266 :data:`PREFERRED_URL_SCHEME` if no request context is available.267 This also can be set to an empty string to build protocol-relative268 URLs.269 :param _anchor: if provided this is added as anchor to the URL.270 :param _method: if provided this explicitly specifies an HTTP method.234 .. versionchanged:: 0.9235 Calls ``app.handle_url_build_error`` on build errors.236 """272 appctx = _app_ctx_stack.top273 reqctx = _request_ctx_stack.top237 return current_app.url_for(238 endpoint,239 _anchor=_anchor,240 _method=_method,241 _scheme=_scheme,242 _external=_external,243 **values,244 )245275 if appctx is None:276 raise RuntimeError(277 "Attempted to generate a URL without the application context being"278 " pushed. This has to be executed when application context is"279 " available."280 )246282 # If request specific information is available we have some extra283 # features that support "relative" URLs.284 if reqctx is not None:285 url_adapter = reqctx.url_adapter286 blueprint_name = request.blueprint287288 if endpoint[:1] == ".":289 if blueprint_name is not None:290 endpoint = f"{blueprint_name}{endpoint}"291 else:292 endpoint = endpoint[1:]293294 external = values.pop("_external", False)295296 # Otherwise go with the url adapter from the appctx and make297 # the URLs external by default.298 else:299 url_adapter = appctx.url_adapter300301 if url_adapter is None:302 raise RuntimeError(303 "Application was not able to create a URL adapter for request"304 " independent URL generation. You might be able to fix this by"305 " setting the SERVER_NAME config variable."306 )307308 external = values.pop("_external", True)309310 anchor = values.pop("_anchor", None)311 method = values.pop("_method", None)312 scheme = values.pop("_scheme", None)313 appctx.app.inject_url_defaults(endpoint, values)314315 # This is not the best way to deal with this but currently the316 # underlying Werkzeug router does not support overriding the scheme on317 # a per build call basis.318 old_scheme = None319 if scheme is not None:320 if not external:321 raise ValueError("When specifying _scheme, _external must be True")322 old_scheme = url_adapter.url_scheme323 url_adapter.url_scheme = scheme324325 try:326 try:327 rv = url_adapter.build(328 endpoint, values, method=method, force_external=external329 )330 finally:331 if old_scheme is not None:332 url_adapter.url_scheme = old_scheme333 except BuildError as error:334 # We need to inject the values again so that the app callback can335 # deal with that sort of stuff.336 values["_external"] = external337 values["_anchor"] = anchor338 values["_method"] = method339 values["_scheme"] = scheme340 return appctx.app.handle_url_build_error(error, endpoint, values)341342 if anchor is not None:343 rv += f"#{url_quote(anchor)}"344 return rv345346247def redirect(248 location: str, code: int = 302, Response: t.Optional[t.Type["BaseResponse"]] = None249) -> "BaseResponse":250 """Create a redirect response object.
493 unmodified lines
modified:tests/test_helpers.py+8 added-4 removed
117 unmodified lines
118 == "https://localhost/"119 )120121 def test_url_for_with_scheme_not_external(self, app, req_ctx):122 @app.route("/")123 def index():124 return "42"122 app.add_url_rule("/", endpoint="index")123126 pytest.raises(ValueError, flask.url_for, "index", _scheme="https")124 # Implicit external with scheme.125 url = flask.url_for("index", _scheme="https")126 assert url == "https://localhost/"127128 # Error when external=False with scheme129 with pytest.raises(ValueError):130 flask.url_for("index", _scheme="https", _external=False)131132 def test_url_for_with_alternating_schemes(self, app, req_ctx):133 @app.route("/")134 def index():135 return "42"
228 unmodified lines