1
0

servlet.py 6.9 KB

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