Document url_for BuildError hook.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Ron DuPlain · committed by Ron DuPlain · parent ccc6816 · Browse files · 2 files·+35 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+35 added−0 removed
- other:+35 added−0 removed
Provenance
- Commit
148c50a- Tree
679929b- Author
Ron DuPlain <ron.duplain@gmail.com>- Committer
Ron DuPlain <ron.duplain@gmail.com>- Parent
ccc6816
2 files changed+35 added−0 removed
modified:flask/app.py+1 added
1490 unmodified lines1491 """1492 if self.build_error_handler is None:1493 exc_type, exc_value, tb = sys.exc_info()1494 if exc_value is error:1495+ # exception is current, raise in context of original traceback.1496 raise exc_type, exc_value, tb1497 else:1498 raise error1499 return self.build_error_handler(error, endpoint, **values)186 unmodified linesmodified:flask/helpers.py+34 added
210 unmodified lines211 url_for('.index')212 213 For more information, head over to the :ref:`Quickstart <url-building>`.214 215+ To integrate applications, :class:`Flask` has a hook to intercept URL build216+ errors through :attr:`Flask.build_error_handler`. The `url_for` function217+ results in a :exc:`~werkzeug.routing.BuildError` when the current app does218+ not have a URL for the given endpoint and values. When it does, the219+ :data:`~flask.current_app` calls its :attr:`~Flask.build_error_handler` if220+ it is not `None`, which can return a string to use as the result of221+ `url_for` (instead of `url_for`'s default to raise the222+ :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.223+ An example::224+225+ def external_url_handler(error, endpoint, **values):226+ "Looks up an external URL when `url_for` cannot build a URL."227+ # This is an example of hooking the build_error_handler.228+ # Here, lookup_url is some utility function you've built229+ # which looks up the endpoint in some external URL registry.230+ url = lookup_url(endpoint, **values)231+ if url is None:232+ # External lookup did not have a URL.233+ # Re-raise the BuildError, in context of original traceback.234+ exc_type, exc_value, tb = sys.exc_info()235+ if exc_value is error:236+ raise exc_type, exc_value, tb237+ else:238+ raise error239+ # url_for will use this result, instead of raising BuildError.240+ return url241+242+ app.build_error_handler = external_url_handler243+244+ Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and245+ `endpoint` and `**values` are the arguments passed into `url_for`. Note246+ that this is for building URLs outside the current application, and not for247+ handling 404 NotFound errors.248+249 .. versionadded:: 0.9250 The `_anchor` and `_method` parameters were added.251 252 .. versionadded:: 0.9564 unmodified lines