Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import types
- from flask import Blueprint
- from flask.views import MethodView
- # decorator code
- def class_route(self, rule, endpoint, **options):
- """
- This decorator allow add routed to class view.
- :param self: any flask object that have `add_url_rule` method.
- :param rule: flask url rule.
- :param endpoint: endpoint name
- """
- def decorator(cls):
- self.add_url_rule(rule, view_func=cls.as_view(endpoint), **options)
- return cls
- return decorator
- # Usage
- # I use `Blueprint` and `MethodView`, but it should work correct with `App` and `View` to.
- bp = Blueprint("bp", __name__, template_folder="templates")
- @class_route(bp, "/", "my_view")
- class MyView(MethodView):
- def get(self):
- return "Hello world"
- # Advanced usage
- # Add decorator as class method
- bp.class_route = types.MethodType(class_route, bp)
- # And use is as bultin decorator
- @bp.class_route("/advanced", "advanced_my_view")
- class AdvancedMyView(MethodView):
- def get(self):
- return "Hello world!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement