You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
5.7KB

  1. import typing as t
  2. from .globals import request
  3. from .typing import ResponseReturnValue
  4. http_method_funcs = frozenset(
  5. ["get", "post", "head", "options", "delete", "put", "trace", "patch"]
  6. )
  7. class View:
  8. """Alternative way to use view functions. A subclass has to implement
  9. :meth:`dispatch_request` which is called with the view arguments from
  10. the URL routing system. If :attr:`methods` is provided the methods
  11. do not have to be passed to the :meth:`~flask.Flask.add_url_rule`
  12. method explicitly::
  13. class MyView(View):
  14. methods = ['GET']
  15. def dispatch_request(self, name):
  16. return f"Hello {name}!"
  17. app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))
  18. When you want to decorate a pluggable view you will have to either do that
  19. when the view function is created (by wrapping the return value of
  20. :meth:`as_view`) or you can use the :attr:`decorators` attribute::
  21. class SecretView(View):
  22. methods = ['GET']
  23. decorators = [superuser_required]
  24. def dispatch_request(self):
  25. ...
  26. The decorators stored in the decorators list are applied one after another
  27. when the view function is created. Note that you can *not* use the class
  28. based decorators since those would decorate the view class and not the
  29. generated view function!
  30. """
  31. #: A list of methods this view can handle.
  32. methods: t.Optional[t.List[str]] = None
  33. #: Setting this disables or force-enables the automatic options handling.
  34. provide_automatic_options: t.Optional[bool] = None
  35. #: The canonical way to decorate class-based views is to decorate the
  36. #: return value of as_view(). However since this moves parts of the
  37. #: logic from the class declaration to the place where it's hooked
  38. #: into the routing system.
  39. #:
  40. #: You can place one or more decorators in this list and whenever the
  41. #: view function is created the result is automatically decorated.
  42. #:
  43. #: .. versionadded:: 0.8
  44. decorators: t.List[t.Callable] = []
  45. def dispatch_request(self) -> ResponseReturnValue:
  46. """Subclasses have to override this method to implement the
  47. actual view function code. This method is called with all
  48. the arguments from the URL rule.
  49. """
  50. raise NotImplementedError()
  51. @classmethod
  52. def as_view(
  53. cls, name: str, *class_args: t.Any, **class_kwargs: t.Any
  54. ) -> t.Callable:
  55. """Converts the class into an actual view function that can be used
  56. with the routing system. Internally this generates a function on the
  57. fly which will instantiate the :class:`View` on each request and call
  58. the :meth:`dispatch_request` method on it.
  59. The arguments passed to :meth:`as_view` are forwarded to the
  60. constructor of the class.
  61. """
  62. def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:
  63. self = view.view_class(*class_args, **class_kwargs) # type: ignore
  64. return self.dispatch_request(*args, **kwargs)
  65. if cls.decorators:
  66. view.__name__ = name
  67. view.__module__ = cls.__module__
  68. for decorator in cls.decorators:
  69. view = decorator(view)
  70. # We attach the view class to the view function for two reasons:
  71. # first of all it allows us to easily figure out what class-based
  72. # view this thing came from, secondly it's also used for instantiating
  73. # the view class so you can actually replace it with something else
  74. # for testing purposes and debugging.
  75. view.view_class = cls # type: ignore
  76. view.__name__ = name
  77. view.__doc__ = cls.__doc__
  78. view.__module__ = cls.__module__
  79. view.methods = cls.methods # type: ignore
  80. view.provide_automatic_options = cls.provide_automatic_options # type: ignore
  81. return view
  82. class MethodViewType(type):
  83. """Metaclass for :class:`MethodView` that determines what methods the view
  84. defines.
  85. """
  86. def __init__(cls, name, bases, d):
  87. super().__init__(name, bases, d)
  88. if "methods" not in d:
  89. methods = set()
  90. for base in bases:
  91. if getattr(base, "methods", None):
  92. methods.update(base.methods)
  93. for key in http_method_funcs:
  94. if hasattr(cls, key):
  95. methods.add(key.upper())
  96. # If we have no method at all in there we don't want to add a
  97. # method list. This is for instance the case for the base class
  98. # or another subclass of a base method view that does not introduce
  99. # new methods.
  100. if methods:
  101. cls.methods = methods
  102. class MethodView(View, metaclass=MethodViewType):
  103. """A class-based view that dispatches request methods to the corresponding
  104. class methods. For example, if you implement a ``get`` method, it will be
  105. used to handle ``GET`` requests. ::
  106. class CounterAPI(MethodView):
  107. def get(self):
  108. return session.get('counter', 0)
  109. def post(self):
  110. session['counter'] = session.get('counter', 0) + 1
  111. return 'OK'
  112. app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))
  113. """
  114. def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:
  115. meth = getattr(self, request.method.lower(), None)
  116. # If the request method is HEAD and we don't have a handler for it
  117. # retry with GET.
  118. if meth is None and request.method == "HEAD":
  119. meth = getattr(self, "get", None)
  120. assert meth is not None, f"Unimplemented method {request.method!r}"
  121. return meth(*args, **kwargs)