Generates a URL to the given endpoint with the method provided.
Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is
None, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (
This will reference the index function local to the current blueprint:
For more information, head over to the Quickstart.
To integrate applications,
Flaskhas a hook to intercept URL build errors through
Flask.url_build_error_handlers. The url_for function results in a
BuildErrorwhen the current app does not have a URL for the given endpoint and values. When it does, the
url_build_error_handlersif it is not
None, which can return a string to use as the result of url_for (instead of url_for‘s default to raise the
BuildErrorexception) or re-raise the exception. An example:
def external_url_handler(error, endpoint, values): "Looks up an external URL when `url_for` cannot build a URL." # This is an example of hooking the build_error_handler. # Here, lookup_url is some utility function you've built # which looks up the endpoint in some external URL registry. url = lookup_url(endpoint, **values) if url is None: # External lookup did not have a URL. # Re-raise the BuildError, in context of original traceback. exc_type, exc_value, tb = sys.exc_info() if exc_value is error: raise exc_type, exc_value, tb else: raise error # url_for will use this result, instead of raising BuildError. return url app.url_build_error_handlers.append(external_url_handler)
Here, error is the instance of
BuildError, and endpoint and values are the arguments passed into url_for. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors.
New in version 0.10: The _scheme parameter was added.
New in version 0.9: The _anchor and _method parameters were added.
New in version 0.9: Calls
- endpoint – the endpoint of the URL (name of the function)
- values – the variable arguments of the URL rule
- _external – if set to
True, an absolute URL is generated. Server address can be changed via
SERVER_NAMEconfiguration variable which defaults to localhost.
- _scheme – a string specifying the desired URL scheme. The _external
parameter must be set to
ValueErroris raised. The default behavior uses the same scheme as the current request, or
PREFERRED_URL_SCHEMEfrom the app configuration if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
- _anchor – if provided this is added as anchor to the URL.
- _method – if provided this explicitly specifies an HTTP method.