servlet.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """ This module contains base REST classes for constructing REST servlets. """
  16. from synapse.api.errors import SynapseError, Codes
  17. import logging
  18. import simplejson
  19. logger = logging.getLogger(__name__)
  20. def parse_integer(request, name, default=None, required=False):
  21. """Parse an integer parameter from the request string
  22. Args:
  23. request: the twisted HTTP request.
  24. name (str): the name of the query parameter.
  25. default (int|None): value to use if the parameter is absent, defaults
  26. to None.
  27. required (bool): whether to raise a 400 SynapseError if the
  28. parameter is absent, defaults to False.
  29. Returns:
  30. int|None: An int value or the default.
  31. Raises:
  32. SynapseError: if the parameter is absent and required, or if the
  33. parameter is present and not an integer.
  34. """
  35. return parse_integer_from_args(request.args, name, default, required)
  36. def parse_integer_from_args(args, name, default=None, required=False):
  37. if name in args:
  38. try:
  39. return int(args[name][0])
  40. except Exception:
  41. message = "Query parameter %r must be an integer" % (name,)
  42. raise SynapseError(400, message)
  43. else:
  44. if required:
  45. message = "Missing integer query parameter %r" % (name,)
  46. raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
  47. else:
  48. return default
  49. def parse_boolean(request, name, default=None, required=False):
  50. """Parse a boolean parameter from the request query string
  51. Args:
  52. request: the twisted HTTP request.
  53. name (str): the name of the query parameter.
  54. default (bool|None): value to use if the parameter is absent, defaults
  55. to None.
  56. required (bool): whether to raise a 400 SynapseError if the
  57. parameter is absent, defaults to False.
  58. Returns:
  59. bool|None: A bool value or the default.
  60. Raises:
  61. SynapseError: if the parameter is absent and required, or if the
  62. parameter is present and not one of "true" or "false".
  63. """
  64. return parse_boolean_from_args(request.args, name, default, required)
  65. def parse_boolean_from_args(args, name, default=None, required=False):
  66. if name in args:
  67. try:
  68. return {
  69. "true": True,
  70. "false": False,
  71. }[args[name][0]]
  72. except Exception:
  73. message = (
  74. "Boolean query parameter %r must be one of"
  75. " ['true', 'false']"
  76. ) % (name,)
  77. raise SynapseError(400, message)
  78. else:
  79. if required:
  80. message = "Missing boolean query parameter %r" % (name,)
  81. raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
  82. else:
  83. return default
  84. def parse_string(request, name, default=None, required=False,
  85. allowed_values=None, param_type="string"):
  86. """Parse a string parameter from the request query string.
  87. Args:
  88. request: the twisted HTTP request.
  89. name (str): the name of the query parameter.
  90. default (str|None): value to use if the parameter is absent, defaults
  91. to None.
  92. required (bool): whether to raise a 400 SynapseError if the
  93. parameter is absent, defaults to False.
  94. allowed_values (list[str]): List of allowed values for the string,
  95. or None if any value is allowed, defaults to None
  96. Returns:
  97. str|None: A string value or the default.
  98. Raises:
  99. SynapseError if the parameter is absent and required, or if the
  100. parameter is present, must be one of a list of allowed values and
  101. is not one of those allowed values.
  102. """
  103. return parse_string_from_args(
  104. request.args, name, default, required, allowed_values, param_type,
  105. )
  106. def parse_string_from_args(args, name, default=None, required=False,
  107. allowed_values=None, param_type="string"):
  108. if name in args:
  109. value = args[name][0]
  110. if allowed_values is not None and value not in allowed_values:
  111. message = "Query parameter %r must be one of [%s]" % (
  112. name, ", ".join(repr(v) for v in allowed_values)
  113. )
  114. raise SynapseError(400, message)
  115. else:
  116. return value
  117. else:
  118. if required:
  119. message = "Missing %s query parameter %r" % (param_type, name)
  120. raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
  121. else:
  122. return default
  123. def parse_json_value_from_request(request, allow_empty_body=False):
  124. """Parse a JSON value from the body of a twisted HTTP request.
  125. Args:
  126. request: the twisted HTTP request.
  127. allow_empty_body (bool): if True, an empty body will be accepted and
  128. turned into None
  129. Returns:
  130. The JSON value.
  131. Raises:
  132. SynapseError if the request body couldn't be decoded as JSON.
  133. """
  134. try:
  135. content_bytes = request.content.read()
  136. except Exception:
  137. raise SynapseError(400, "Error reading JSON content.")
  138. if not content_bytes and allow_empty_body:
  139. return None
  140. try:
  141. content = simplejson.loads(content_bytes)
  142. except Exception as e:
  143. logger.warn("Unable to parse JSON: %s", e)
  144. raise SynapseError(400, "Content not JSON.", errcode=Codes.NOT_JSON)
  145. return content
  146. def parse_json_object_from_request(request, allow_empty_body=False):
  147. """Parse a JSON object from the body of a twisted HTTP request.
  148. Args:
  149. request: the twisted HTTP request.
  150. allow_empty_body (bool): if True, an empty body will be accepted and
  151. turned into an empty dict.
  152. Raises:
  153. SynapseError if the request body couldn't be decoded as JSON or
  154. if it wasn't a JSON object.
  155. """
  156. content = parse_json_value_from_request(
  157. request, allow_empty_body=allow_empty_body,
  158. )
  159. if allow_empty_body and content is None:
  160. return {}
  161. if type(content) != dict:
  162. message = "Content must be a JSON object."
  163. raise SynapseError(400, message, errcode=Codes.BAD_JSON)
  164. return content
  165. def assert_params_in_request(body, required):
  166. absent = []
  167. for k in required:
  168. if k not in body:
  169. absent.append(k)
  170. if len(absent) > 0:
  171. raise SynapseError(400, "Missing params: %r" % absent, Codes.MISSING_PARAM)
  172. class RestServlet(object):
  173. """ A Synapse REST Servlet.
  174. An implementing class can either provide its own custom 'register' method,
  175. or use the automatic pattern handling provided by the base class.
  176. To use this latter, the implementing class instead provides a `PATTERN`
  177. class attribute containing a pre-compiled regular expression. The automatic
  178. register method will then use this method to register any of the following
  179. instance methods associated with the corresponding HTTP method:
  180. on_GET
  181. on_PUT
  182. on_POST
  183. on_DELETE
  184. on_OPTIONS
  185. Automatically handles turning CodeMessageExceptions thrown by these methods
  186. into the appropriate HTTP response.
  187. """
  188. def register(self, http_server):
  189. """ Register this servlet with the given HTTP server. """
  190. if hasattr(self, "PATTERNS"):
  191. patterns = self.PATTERNS
  192. for method in ("GET", "PUT", "POST", "OPTIONS", "DELETE"):
  193. if hasattr(self, "on_%s" % (method,)):
  194. method_handler = getattr(self, "on_%s" % (method,))
  195. http_server.register_paths(method, patterns, method_handler)
  196. else:
  197. raise NotImplementedError("RestServlet must register something.")