forked from gergely/calendar-social
Create the RoutedMixin class
It will be used both in the app, and later blueprint classes.
This commit is contained in:
@@ -68,3 +68,51 @@ def force_locale(locale):
|
||||
babel.locale_selector_func = orig_locale_selector_func
|
||||
for key, value in orig_attrs.items():
|
||||
setattr(ctx, key, value)
|
||||
|
||||
|
||||
class RoutedMixin:
|
||||
"""Mixin to lazily register class methods as routes
|
||||
|
||||
Works both for `Flask` and `Blueprint` objects.
|
||||
|
||||
Example::
|
||||
|
||||
class MyBlueprint(Blueprint, RoutedMixin):
|
||||
def __init__(self, *args, **kwargs):
|
||||
do_whatever_you_like()
|
||||
|
||||
RoutedMixin.register_routes(self)
|
||||
|
||||
@RoutedMixin.route('/')
|
||||
def index(self):
|
||||
return 'Hello, World!'
|
||||
"""
|
||||
|
||||
def register_routes(self):
|
||||
for attr_name in self.__dir__():
|
||||
attr = getattr(self, attr_name)
|
||||
|
||||
if not callable(attr):
|
||||
continue
|
||||
|
||||
args, kwargs = getattr(attr, 'routing', (None, None))
|
||||
|
||||
if args is None:
|
||||
continue
|
||||
|
||||
self.route(*args, **kwargs)(attr)
|
||||
|
||||
@staticmethod
|
||||
def route(*args, **kwargs):
|
||||
"""Mark a function as a future route
|
||||
|
||||
Such functions will be iterated over when the application is initialised. ``*args`` and
|
||||
``**kwargs`` will be passed verbatim to `Flask.route()`.
|
||||
"""
|
||||
|
||||
def decorator(func): # pylint: disable=missing-docstring
|
||||
setattr(func, 'routing', (args, kwargs))
|
||||
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
Reference in New Issue
Block a user