Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. import types
  2.  
  3. from flask import Blueprint
  4. from flask.views import MethodView
  5.  
  6.  
  7. # decorator code
  8. def class_route(self, rule, endpoint, **options):
  9. """
  10. This decorator allow add routed to class view.
  11. :param self: any flask object that have `add_url_rule` method.
  12. :param rule: flask url rule.
  13. :param endpoint: endpoint name
  14. """
  15.  
  16. def decorator(cls):
  17. self.add_url_rule(rule, view_func=cls.as_view(endpoint), **options)
  18. return cls
  19.  
  20. return decorator
  21.  
  22. # Usage
  23. # I use `Blueprint` and `MethodView`, but it should work correct with `App` and `View` to.
  24.  
  25.  
  26. bp = Blueprint("bp", __name__, template_folder="templates")
  27.  
  28.  
  29. @class_route(bp, "/", "my_view")
  30. class MyView(MethodView):
  31. def get(self):
  32. return "Hello world"
  33.  
  34.  
  35. # Advanced usage
  36. # Add decorator as class method
  37. bp.class_route = types.MethodType(class_route, bp)
  38.  
  39.  
  40. # And use is as bultin decorator
  41. @bp.class_route("/advanced", "advanced_my_view")
  42. class AdvancedMyView(MethodView):
  43. def get(self):
  44. return "Hello world!"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement