daily pastebin goal
45%
SHARE
TWEET

Untitled

a guest Mar 24th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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!"
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top