servlet.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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:
  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. if name in request.args:
  65. try:
  66. return {
  67. "true": True,
  68. "false": False,
  69. }[request.args[name][0]]
  70. except:
  71. message = (
  72. "Boolean query parameter %r must be one of"
  73. " ['true', 'false']"
  74. ) % (name,)
  75. raise SynapseError(400, message)
  76. else:
  77. if required:
  78. message = "Missing boolean query parameter %r" % (name,)
  79. raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
  80. else:
  81. return default
  82. def parse_string(request, name, default=None, required=False,
  83. allowed_values=None, param_type="string"):
  84. """Parse a string parameter from the request query string.
  85. Args:
  86. request: the twisted HTTP request.
  87. name (str): the name of the query parameter.
  88. default (str|None): value to use if the parameter is absent, defaults
  89. to None.
  90. required (bool): whether to raise a 400 SynapseError if the
  91. parameter is absent, defaults to False.
  92. allowed_values (list[str]): List of allowed values for the string,
  93. or None if any value is allowed, defaults to None
  94. Returns:
  95. str|None: A string value or the default.
  96. Raises:
  97. SynapseError if the parameter is absent and required, or if the
  98. parameter is present, must be one of a list of allowed values and
  99. is not one of those allowed values.
  100. """
  101. return parse_string_from_args(
  102. request.args, name, default, required, allowed_values, param_type,
  103. )
  104. def parse_string_from_args(args, name, default=None, required=False,
  105. allowed_values=None, param_type="string"):
  106. if name in args:
  107. value = args[name][0]
  108. if allowed_values is not None and value not in allowed_values:
  109. message = "Query parameter %r must be one of [%s]" % (
  110. name, ", ".join(repr(v) for v in allowed_values)
  111. )
  112. raise SynapseError(400, message)
  113. else:
  114. return value
  115. else:
  116. if required:
  117. message = "Missing %s query parameter %r" % (param_type, name)
  118. raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
  119. else:
  120. return default
  121. def parse_json_value_from_request(request):
  122. """Parse a JSON value from the body of a twisted HTTP request.
  123. Args:
  124. request: the twisted HTTP request.
  125. Returns:
  126. The JSON value.
  127. Raises:
  128. SynapseError if the request body couldn't be decoded as JSON.
  129. """
  130. try:
  131. content_bytes = request.content.read()
  132. except:
  133. raise SynapseError(400, "Error reading JSON content.")
  134. try:
  135. content = simplejson.loads(content_bytes)
  136. except simplejson.JSONDecodeError:
  137. raise SynapseError(400, "Content not JSON.", errcode=Codes.NOT_JSON)
  138. return content
  139. def parse_json_object_from_request(request):
  140. """Parse a JSON object from the body of a twisted HTTP request.
  141. Args:
  142. request: the twisted HTTP request.
  143. Raises:
  144. SynapseError if the request body couldn't be decoded as JSON or
  145. if it wasn't a JSON object.
  146. """
  147. content = parse_json_value_from_request(request)
  148. if type(content) != dict:
  149. message = "Content must be a JSON object."
  150. raise SynapseError(400, message, errcode=Codes.BAD_JSON)
  151. return content
  152. class RestServlet(object):
  153. """ A Synapse REST Servlet.
  154. An implementing class can either provide its own custom 'register' method,
  155. or use the automatic pattern handling provided by the base class.
  156. To use this latter, the implementing class instead provides a `PATTERN`
  157. class attribute containing a pre-compiled regular expression. The automatic
  158. register method will then use this method to register any of the following
  159. instance methods associated with the corresponding HTTP method:
  160. on_GET
  161. on_PUT
  162. on_POST
  163. on_DELETE
  164. on_OPTIONS
  165. Automatically handles turning CodeMessageExceptions thrown by these methods
  166. into the appropriate HTTP response.
  167. """
  168. def register(self, http_server):
  169. """ Register this servlet with the given HTTP server. """
  170. if hasattr(self, "PATTERNS"):
  171. patterns = self.PATTERNS
  172. for method in ("GET", "PUT", "POST", "OPTIONS", "DELETE"):
  173. if hasattr(self, "on_%s" % (method,)):
  174. method_handler = getattr(self, "on_%s" % (method,))
  175. http_server.register_paths(method, patterns, method_handler)
  176. else:
  177. raise NotImplementedError("RestServlet must register something.")