views.py 5.6 KB

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