mirror of https://github.com/pallets/flask.git
Implement the endpoint decorator. This allows you to easily map views to endpoints when using the werkzeug routing.
Signed-off-by: Armin Ronacher <armin.ronacher@active-4.com>
This commit is contained in:
parent
8a73097fe5
commit
b0ca7e5af1
|
@ -145,3 +145,24 @@ Here the code for that decorator::
|
|||
return render_template(template_name, **ctx)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
Endpoint Decorator
|
||||
------------------
|
||||
|
||||
When you want to use the werkzeug routing system for more flexibility you
|
||||
need to map the endpoint as defined in the :class:`~werkzeug.routing.Rule`
|
||||
to a view function. This is possible with this decorator. For example::
|
||||
|
||||
from flask import Flask
|
||||
from werkzeug.routing import Rule
|
||||
|
||||
app = Flask(__name__)
|
||||
app.url_map.add(Rule('/', endpoint='index'))
|
||||
|
||||
@app.endpoint('index')
|
||||
def my_index():
|
||||
return "Hello world"
|
||||
|
||||
|
||||
|
||||
|
|
17
flask/app.py
17
flask/app.py
|
@ -496,6 +496,7 @@ class Flask(_PackageBoundObject):
|
|||
"""
|
||||
options.setdefault('url_prefix', module.url_prefix)
|
||||
options.setdefault('subdomain', module.subdomain)
|
||||
self.view_functions.update(module.view_functions)
|
||||
state = _ModuleSetupState(self, **options)
|
||||
for func in module._register_events:
|
||||
func(state)
|
||||
|
@ -629,6 +630,22 @@ class Flask(_PackageBoundObject):
|
|||
return f
|
||||
return decorator
|
||||
|
||||
|
||||
def endpoint(self, endpoint):
|
||||
"""A decorator to register a function as an endpoint.
|
||||
Example::
|
||||
|
||||
@app.endpoint('example.endpoint')
|
||||
def example():
|
||||
return "example"
|
||||
|
||||
:param endpoint: the name of the endpoint
|
||||
"""
|
||||
def decorator(f):
|
||||
self.view_functions[endpoint] = f
|
||||
return f
|
||||
return decorator
|
||||
|
||||
def errorhandler(self, code):
|
||||
"""A decorator that is used to register a function give a given
|
||||
error code. Example::
|
||||
|
|
|
@ -124,6 +124,7 @@ class Module(_PackageBoundObject):
|
|||
self.name = name
|
||||
self.url_prefix = url_prefix
|
||||
self.subdomain = subdomain
|
||||
self.view_functions = {}
|
||||
self._register_events = [_register_module(self, static_path)]
|
||||
|
||||
def route(self, rule, **options):
|
||||
|
@ -157,6 +158,13 @@ class Module(_PackageBoundObject):
|
|||
view_func, **options)
|
||||
self._record(register_rule)
|
||||
|
||||
def endpoint(self, endpoint):
|
||||
"""Like :meth:`Flask.endpoint` but for a module."""
|
||||
def decorator(f):
|
||||
self.view_functions[endpoint] = f
|
||||
return f
|
||||
return decorator
|
||||
|
||||
def before_request(self, f):
|
||||
"""Like :meth:`Flask.before_request` but for a module. This function
|
||||
is only executed before each request that is handled by a function of
|
||||
|
|
Loading…
Reference in New Issue