views.py 5.7 KB

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