wrappers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.contrib.wrappers
  4. ~~~~~~~~~~~~~~~~~~~~~~~~~
  5. Extra wrappers or mixins contributed by the community. These wrappers can
  6. be mixed in into request objects to add extra functionality.
  7. Example::
  8. from werkzeug.wrappers import Request as RequestBase
  9. from werkzeug.contrib.wrappers import JSONRequestMixin
  10. class Request(RequestBase, JSONRequestMixin):
  11. pass
  12. Afterwards this request object provides the extra functionality of the
  13. :class:`JSONRequestMixin`.
  14. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  15. :license: BSD, see LICENSE for more details.
  16. """
  17. import codecs
  18. try:
  19. from simplejson import loads
  20. except ImportError:
  21. from json import loads
  22. from werkzeug.exceptions import BadRequest
  23. from werkzeug.utils import cached_property
  24. from werkzeug.http import dump_options_header, parse_options_header
  25. from werkzeug._compat import wsgi_decoding_dance
  26. def is_known_charset(charset):
  27. """Checks if the given charset is known to Python."""
  28. try:
  29. codecs.lookup(charset)
  30. except LookupError:
  31. return False
  32. return True
  33. class JSONRequestMixin(object):
  34. """Add json method to a request object. This will parse the input data
  35. through simplejson if possible.
  36. :exc:`~werkzeug.exceptions.BadRequest` will be raised if the content-type
  37. is not json or if the data itself cannot be parsed as json.
  38. """
  39. @cached_property
  40. def json(self):
  41. """Get the result of simplejson.loads if possible."""
  42. if 'json' not in self.environ.get('CONTENT_TYPE', ''):
  43. raise BadRequest('Not a JSON request')
  44. try:
  45. return loads(self.data.decode(self.charset, self.encoding_errors))
  46. except Exception:
  47. raise BadRequest('Unable to read JSON request')
  48. class ProtobufRequestMixin(object):
  49. """Add protobuf parsing method to a request object. This will parse the
  50. input data through `protobuf`_ if possible.
  51. :exc:`~werkzeug.exceptions.BadRequest` will be raised if the content-type
  52. is not protobuf or if the data itself cannot be parsed property.
  53. .. _protobuf: http://code.google.com/p/protobuf/
  54. """
  55. #: by default the :class:`ProtobufRequestMixin` will raise a
  56. #: :exc:`~werkzeug.exceptions.BadRequest` if the object is not
  57. #: initialized. You can bypass that check by setting this
  58. #: attribute to `False`.
  59. protobuf_check_initialization = True
  60. def parse_protobuf(self, proto_type):
  61. """Parse the data into an instance of proto_type."""
  62. if 'protobuf' not in self.environ.get('CONTENT_TYPE', ''):
  63. raise BadRequest('Not a Protobuf request')
  64. obj = proto_type()
  65. try:
  66. obj.ParseFromString(self.data)
  67. except Exception:
  68. raise BadRequest("Unable to parse Protobuf request")
  69. # Fail if not all required fields are set
  70. if self.protobuf_check_initialization and not obj.IsInitialized():
  71. raise BadRequest("Partial Protobuf request")
  72. return obj
  73. class RoutingArgsRequestMixin(object):
  74. """This request mixin adds support for the wsgiorg routing args
  75. `specification`_.
  76. .. _specification: https://wsgi.readthedocs.io/en/latest/specifications/routing_args.html
  77. """
  78. def _get_routing_args(self):
  79. return self.environ.get('wsgiorg.routing_args', (()))[0]
  80. def _set_routing_args(self, value):
  81. if self.shallow:
  82. raise RuntimeError('A shallow request tried to modify the WSGI '
  83. 'environment. If you really want to do that, '
  84. 'set `shallow` to False.')
  85. self.environ['wsgiorg.routing_args'] = (value, self.routing_vars)
  86. routing_args = property(_get_routing_args, _set_routing_args, doc='''
  87. The positional URL arguments as `tuple`.''')
  88. del _get_routing_args, _set_routing_args
  89. def _get_routing_vars(self):
  90. rv = self.environ.get('wsgiorg.routing_args')
  91. if rv is not None:
  92. return rv[1]
  93. rv = {}
  94. if not self.shallow:
  95. self.routing_vars = rv
  96. return rv
  97. def _set_routing_vars(self, value):
  98. if self.shallow:
  99. raise RuntimeError('A shallow request tried to modify the WSGI '
  100. 'environment. If you really want to do that, '
  101. 'set `shallow` to False.')
  102. self.environ['wsgiorg.routing_args'] = (self.routing_args, value)
  103. routing_vars = property(_get_routing_vars, _set_routing_vars, doc='''
  104. The keyword URL arguments as `dict`.''')
  105. del _get_routing_vars, _set_routing_vars
  106. class ReverseSlashBehaviorRequestMixin(object):
  107. """This mixin reverses the trailing slash behavior of :attr:`script_root`
  108. and :attr:`path`. This makes it possible to use :func:`~urlparse.urljoin`
  109. directly on the paths.
  110. Because it changes the behavior or :class:`Request` this class has to be
  111. mixed in *before* the actual request class::
  112. class MyRequest(ReverseSlashBehaviorRequestMixin, Request):
  113. pass
  114. This example shows the differences (for an application mounted on
  115. `/application` and the request going to `/application/foo/bar`):
  116. +---------------+-------------------+---------------------+
  117. | | normal behavior | reverse behavior |
  118. +===============+===================+=====================+
  119. | `script_root` | ``/application`` | ``/application/`` |
  120. +---------------+-------------------+---------------------+
  121. | `path` | ``/foo/bar`` | ``foo/bar`` |
  122. +---------------+-------------------+---------------------+
  123. """
  124. @cached_property
  125. def path(self):
  126. """Requested path as unicode. This works a bit like the regular path
  127. info in the WSGI environment but will not include a leading slash.
  128. """
  129. path = wsgi_decoding_dance(self.environ.get('PATH_INFO') or '',
  130. self.charset, self.encoding_errors)
  131. return path.lstrip('/')
  132. @cached_property
  133. def script_root(self):
  134. """The root path of the script includling a trailing slash."""
  135. path = wsgi_decoding_dance(self.environ.get('SCRIPT_NAME') or '',
  136. self.charset, self.encoding_errors)
  137. return path.rstrip('/') + '/'
  138. class DynamicCharsetRequestMixin(object):
  139. """"If this mixin is mixed into a request class it will provide
  140. a dynamic `charset` attribute. This means that if the charset is
  141. transmitted in the content type headers it's used from there.
  142. Because it changes the behavior or :class:`Request` this class has
  143. to be mixed in *before* the actual request class::
  144. class MyRequest(DynamicCharsetRequestMixin, Request):
  145. pass
  146. By default the request object assumes that the URL charset is the
  147. same as the data charset. If the charset varies on each request
  148. based on the transmitted data it's not a good idea to let the URLs
  149. change based on that. Most browsers assume either utf-8 or latin1
  150. for the URLs if they have troubles figuring out. It's strongly
  151. recommended to set the URL charset to utf-8::
  152. class MyRequest(DynamicCharsetRequestMixin, Request):
  153. url_charset = 'utf-8'
  154. .. versionadded:: 0.6
  155. """
  156. #: the default charset that is assumed if the content type header
  157. #: is missing or does not contain a charset parameter. The default
  158. #: is latin1 which is what HTTP specifies as default charset.
  159. #: You may however want to set this to utf-8 to better support
  160. #: browsers that do not transmit a charset for incoming data.
  161. default_charset = 'latin1'
  162. def unknown_charset(self, charset):
  163. """Called if a charset was provided but is not supported by
  164. the Python codecs module. By default latin1 is assumed then
  165. to not lose any information, you may override this method to
  166. change the behavior.
  167. :param charset: the charset that was not found.
  168. :return: the replacement charset.
  169. """
  170. return 'latin1'
  171. @cached_property
  172. def charset(self):
  173. """The charset from the content type."""
  174. header = self.environ.get('CONTENT_TYPE')
  175. if header:
  176. ct, options = parse_options_header(header)
  177. charset = options.get('charset')
  178. if charset:
  179. if is_known_charset(charset):
  180. return charset
  181. return self.unknown_charset(charset)
  182. return self.default_charset
  183. class DynamicCharsetResponseMixin(object):
  184. """If this mixin is mixed into a response class it will provide
  185. a dynamic `charset` attribute. This means that if the charset is
  186. looked up and stored in the `Content-Type` header and updates
  187. itself automatically. This also means a small performance hit but
  188. can be useful if you're working with different charsets on
  189. responses.
  190. Because the charset attribute is no a property at class-level, the
  191. default value is stored in `default_charset`.
  192. Because it changes the behavior or :class:`Response` this class has
  193. to be mixed in *before* the actual response class::
  194. class MyResponse(DynamicCharsetResponseMixin, Response):
  195. pass
  196. .. versionadded:: 0.6
  197. """
  198. #: the default charset.
  199. default_charset = 'utf-8'
  200. def _get_charset(self):
  201. header = self.headers.get('content-type')
  202. if header:
  203. charset = parse_options_header(header)[1].get('charset')
  204. if charset:
  205. return charset
  206. return self.default_charset
  207. def _set_charset(self, charset):
  208. header = self.headers.get('content-type')
  209. ct, options = parse_options_header(header)
  210. if not ct:
  211. raise TypeError('Cannot set charset if Content-Type '
  212. 'header is missing.')
  213. options['charset'] = charset
  214. self.headers['Content-Type'] = dump_options_header(ct, options)
  215. charset = property(_get_charset, _set_charset, doc="""
  216. The charset for the response. It's stored inside the
  217. Content-Type header as a parameter.""")
  218. del _get_charset, _set_charset