finish moving url_for to app
Before adoption: this commit came in with the history the project adopted, so no landing records it.
move entire implementation to app make special build args actual keyword-only args handle no app context in method mention other config in server_name error implicit external with scheme use adapter.build url_scheme argument rewrite documentation
authored by David Lord · committed by David Lord · parent 92acd05 · Browse files · 3 files·+185 added−152 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+185 added−152 removed
- tests:+8 added−4 removed
- other:+177 added−148 removed
Provenance
- Commit
39f9363- Tree
27b5d6b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
92acd05
3 files changed+185 added−152 removed
modified:src/flask/app.py+132 added-39 removed
32 unmodified lines33 from .config import ConfigAttribute34 from .ctx import _AppCtxGlobals35 from .ctx import AppContext36 from .ctx import RequestContext37+from .globals import _app_ctx_stack38 from .globals import _request_ctx_stack39 from .globals import g40 from .globals import request41 from .globals import session398 unmodified lines440 #:441 #: .. versionadded:: 2.2442 self.aborter = self.make_aborter()443 443- #: A list of functions that are called when :meth:`url_for` raises a444- #: :exc:`~werkzeug.routing.BuildError`. Each function registered here445- #: is called with `error`, `endpoint` and `values`. If a function446- #: returns ``None`` or raises a :exc:`BuildError` the next function is447- #: 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[451- t.Callable[[Exception, str, dict], str]453+ t.Callable[[Exception, str, t.Dict[str, t.Any]], str]454 ] = []455 456 #: A list of functions that will be called at the beginning of the457 #: first request to this instance. To register a function, use the1208 unmodified lines1666 1667 def url_for(1668 self,1669 endpoint: str,1668- external: bool,1669- url_adapter,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.1678 1673- anchor = values.pop("_anchor", None)1674- method = values.pop("_method", None)1675- scheme = values.pop("_scheme", None)1676- self.inject_url_defaults(endpoint, values)1679+ This is called by :func:`flask.url_for`, and can be called1680+ directly as well.1681 1678- # This is not the best way to deal with this but currently the1679- # underlying Werkzeug router does not support overriding the scheme on1680- # a per build call basis.1681- old_scheme = None1682- if scheme is not None:1683- if not external:1684- raise ValueError("When specifying _scheme, _external must be True")1685- old_scheme = url_adapter.url_scheme1686- url_adapter.url_scheme = scheme1682+ 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.1687 1688- try:1689- try:1690- rv = url_adapter.build(1691- endpoint, values, method=method, force_external=external1688+ 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.1695+1696+ Functions can be decorated with :meth:`url_defaults` to modify1697+ keyword arguments before the URL is built.1698+1699+ 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.1703+1704+ :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``.1719+1720+ .. versionadded:: 2.21721+ Moved from ``flask.url_for``, which calls this method.1722+ """1723+ req_ctx = _request_ctx_stack.top1724+1725+ if req_ctx is not None:1726+ url_adapter = req_ctx.url_adapter1727+ blueprint_name = req_ctx.request.blueprint1728+1729+ # 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:]1736+1737+ # 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.top1743+1744+ # 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)1751+1752+ 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 )1693- finally:1694- if old_scheme is not None:1695- url_adapter.url_scheme = old_scheme1759+1760+ # When outside a request, generate a URL with scheme and1761+ # domain by default.1762+ if _external is None:1763+ _external = True1764+1765+ # 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.")1769+1770+ self.inject_url_defaults(endpoint, values)1771+1772+ 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:1697- # We need to inject the values again so that the app callback can1698- # deal with that sort of stuff.1699- values["_external"] = external1700- values["_anchor"] = anchor1701- values["_method"] = method1702- values["_scheme"] = scheme1781+ values.update(1782+ _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external1783+ )1784 return self.handle_url_build_error(error, endpoint, values)1785 1705- if anchor is not None:1706- rv += f"#{url_quote(anchor)}"1786+ if _anchor is not None:1787+ rv = f"{rv}#{url_quote(_anchor)}"1788+1789 return rv1790 1791 def redirect(self, location: str, code: int = 302) -> BaseResponse:1792 """Create a redirect response object.193 unmodified lines1986 for func in self.url_default_functions[name]:1987 func(endpoint, values)1988 1989 def handle_url_build_error(1908- self, error: Exception, endpoint: str, values: dict1990+ self, error: BuildError, endpoint: str, values: t.Dict[str, t.Any]1991 ) -> str:1910- """Handle :class:`~werkzeug.routing.BuildError` on1911- :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.1996+1997+ 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``.2001+2002+ :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 linesmodified:src/flask/helpers.py+45 added-109 removed
11 unmodified lines12 import werkzeug.utils13 from werkzeug.exceptions import abort as _wz_abort14 from werkzeug.utils import redirect as _wz_redirect15 16-from .globals import _app_ctx_stack16 from .globals import _request_ctx_stack17 from .globals import current_app18 from .globals import request19 from .globals import session169 unmodified lines189 args = args[0]190 return current_app.make_response(args) # type: ignore191 192 194-def url_for(endpoint: str, **values: t.Any) -> str:195- """Generates a URL to the given endpoint with the method provided.193+def 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.203 197- Variable arguments that are unknown to the target endpoint are appended198- to the generated URL as query arguments. If the value of a query argument199- is ``None``, the whole pair is skipped. In case blueprints are active200- you can shortcut references to the same blueprint by prefixing the201- 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.207 203- 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``.223 205- url_for('.index')224+ .. versionchanged:: 2.2225+ Calls ``current_app.url_for``, allowing an app to override the226+ behavior.227 207- See :ref:`url-building`.228+ .. versionchanged:: 0.10229+ The ``_scheme`` parameter was added.230 209- Configuration values ``APPLICATION_ROOT`` and ``SERVER_NAME`` are only used when210- generating URLs outside of a request context.231+ .. versionchanged:: 0.9232+ The ``_anchor`` and ``_method`` parameters were added.233 212- To integrate applications, :class:`Flask` has a hook to intercept URL build213- errors through :attr:`Flask.url_build_error_handlers`. The `url_for`214- function results in a :exc:`~werkzeug.routing.BuildError` when the current215- app does not have a URL for the given endpoint and values. When it does, the216- :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if217- it is not ``None``, which can return a string to use as the result of218- `url_for` (instead of `url_for`'s default to raise the219- :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.220- An example::221-222- def external_url_handler(error, endpoint, values):223- "Looks up an external URL when `url_for` cannot build a URL."224- # This is an example of hooking the build_error_handler.225- # Here, lookup_url is some utility function you've built226- # which looks up the endpoint in some external URL registry.227- url = lookup_url(endpoint, **values)228- if url is None:229- # External lookup did not have a URL.230- # Re-raise the BuildError, in context of original traceback.231- exc_type, exc_value, tb = sys.exc_info()232- if exc_value is error:233- raise exc_type(exc_value).with_traceback(tb)234- else:235- raise error236- # url_for will use this result, instead of raising BuildError.237- return url238-239- app.url_build_error_handlers.append(external_url_handler)240-241- Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and242- `endpoint` and `values` are the arguments passed into `url_for`. Note243- that this is for building URLs outside the current application, and not for244- handling 404 NotFound errors.245-246- .. versionadded:: 0.10247- The `_scheme` parameter was added.248-249- .. versionadded:: 0.9250- The `_anchor` and `_method` parameters were added.251-252- .. versionadded:: 0.9253- Calls :meth:`Flask.handle_build_error` on254- :exc:`~werkzeug.routing.BuildError`.255-256- :param endpoint: the endpoint of the URL (name of the function)257- :param values: the variable arguments of the URL rule258- :param _external: if set to ``True``, an absolute URL is generated. Server259- address can be changed via ``SERVER_NAME`` configuration variable which260- falls back to the `Host` header, then to the IP and port of the request.261- :param _scheme: a string specifying the desired URL scheme. The `_external`262- parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default263- behavior uses the same scheme as the current request, or264- :data:`PREFERRED_URL_SCHEME` if no request context is available.265- This also can be set to an empty string to build protocol-relative266- URLs.267- :param _anchor: if provided this is added as anchor to the URL.268- :param _method: if provided this explicitly specifies an HTTP method.234+ .. versionchanged:: 0.9235+ Calls ``app.handle_url_build_error`` on build errors.236 """270- appctx = _app_ctx_stack.top271- 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+ )245 273- if appctx is None:274- raise RuntimeError(275- "Attempted to generate a URL without the application context being"276- " pushed. This has to be executed when application context is"277- " available."278- )246 280- # If request specific information is available we have some extra281- # features that support "relative" URLs.282- if reqctx is not None:283- url_adapter = reqctx.url_adapter284- blueprint_name = request.blueprint285-286- if endpoint[:1] == ".":287- if blueprint_name is not None:288- endpoint = f"{blueprint_name}{endpoint}"289- else:290- endpoint = endpoint[1:]291-292- external = values.pop("_external", False)293-294- # Otherwise go with the url adapter from the appctx and make295- # the URLs external by default.296- else:297- url_adapter = appctx.url_adapter298-299- if url_adapter is None:300- raise RuntimeError(301- "Application was not able to create a URL adapter for request"302- " independent URL generation. You might be able to fix this by"303- " setting the SERVER_NAME config variable."304- )305-306- external = values.pop("_external", True)307-308- return current_app.url_for(endpoint, external, url_adapter, **values)309-310-247 def redirect(248 location: str, code: int = 302, Response: t.Optional[t.Type["BaseResponse"]] = None249 ) -> "BaseResponse":250 """Create a redirect response object.493 unmodified linesmodified:tests/test_helpers.py+8 added-4 removed
117 unmodified lines118 == "https://localhost/"119 )120 121 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")123 126- 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/"127 128+ # Error when external=False with scheme129+ with pytest.raises(ValueError):130+ flask.url_for("index", _scheme="https", _external=False)131+132 def test_url_for_with_alternating_schemes(self, app, req_ctx):133 @app.route("/")134 def index():135 return "42"228 unmodified lines