serialize.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. # Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. """Protocol input serializes.
  14. This module contains classes that implement input serialization
  15. for the various AWS protocol types.
  16. These classes essentially take user input, a model object that
  17. represents what the expected input should look like, and it returns
  18. a dictionary that contains the various parts of a request. A few
  19. high level design decisions:
  20. * Each protocol type maps to a separate class, all inherit from
  21. ``Serializer``.
  22. * The return value for ``serialize_to_request`` (the main entry
  23. point) returns a dictionary that represents a request. This
  24. will have keys like ``url_path``, ``query_string``, etc. This
  25. is done so that it's a) easy to test and b) not tied to a
  26. particular HTTP library. See the ``serialize_to_request`` docstring
  27. for more details.
  28. Unicode
  29. -------
  30. The input to the serializers should be text (str/unicode), not bytes,
  31. with the exception of blob types. Those are assumed to be binary,
  32. and if a str/unicode type is passed in, it will be encoded as utf-8.
  33. """
  34. import re
  35. import base64
  36. import calendar
  37. import datetime
  38. from xml.etree import ElementTree
  39. from botocore.compat import six
  40. from botocore.compat import json, formatdate
  41. from botocore.utils import parse_to_aware_datetime
  42. from botocore.utils import percent_encode
  43. from botocore.utils import is_json_value_header
  44. from botocore.utils import conditionally_calculate_md5
  45. from botocore import validate
  46. # From the spec, the default timestamp format if not specified is iso8601.
  47. DEFAULT_TIMESTAMP_FORMAT = 'iso8601'
  48. ISO8601 = '%Y-%m-%dT%H:%M:%SZ'
  49. # Same as ISO8601, but with microsecond precision.
  50. ISO8601_MICRO = '%Y-%m-%dT%H:%M:%S.%fZ'
  51. def create_serializer(protocol_name, include_validation=True):
  52. # TODO: Unknown protocols.
  53. serializer = SERIALIZERS[protocol_name]()
  54. if include_validation:
  55. validator = validate.ParamValidator()
  56. serializer = validate.ParamValidationDecorator(validator, serializer)
  57. return serializer
  58. class Serializer(object):
  59. DEFAULT_METHOD = 'POST'
  60. # Clients can change this to a different MutableMapping
  61. # (i.e OrderedDict) if they want. This is used in the
  62. # compliance test to match the hash ordering used in the
  63. # tests.
  64. MAP_TYPE = dict
  65. DEFAULT_ENCODING = 'utf-8'
  66. def serialize_to_request(self, parameters, operation_model):
  67. """Serialize parameters into an HTTP request.
  68. This method takes user provided parameters and a shape
  69. model and serializes the parameters to an HTTP request.
  70. More specifically, this method returns information about
  71. parts of the HTTP request, it does not enforce a particular
  72. interface or standard for an HTTP request. It instead returns
  73. a dictionary of:
  74. * 'url_path'
  75. * 'host_prefix'
  76. * 'query_string'
  77. * 'headers'
  78. * 'body'
  79. * 'method'
  80. It is then up to consumers to decide how to map this to a Request
  81. object of their HTTP library of choice. Below is an example
  82. return value::
  83. {'body': {'Action': 'OperationName',
  84. 'Bar': 'val2',
  85. 'Foo': 'val1',
  86. 'Version': '2014-01-01'},
  87. 'headers': {},
  88. 'method': 'POST',
  89. 'query_string': '',
  90. 'host_prefix': 'value.',
  91. 'url_path': '/'}
  92. :param parameters: The dictionary input parameters for the
  93. operation (i.e the user input).
  94. :param operation_model: The OperationModel object that describes
  95. the operation.
  96. """
  97. raise NotImplementedError("serialize_to_request")
  98. def _create_default_request(self):
  99. # Creates a boilerplate default request dict that subclasses
  100. # can use as a starting point.
  101. serialized = {
  102. 'url_path': '/',
  103. 'query_string': '',
  104. 'method': self.DEFAULT_METHOD,
  105. 'headers': {},
  106. # An empty body is represented as an empty byte string.
  107. 'body': b''
  108. }
  109. return serialized
  110. # Some extra utility methods subclasses can use.
  111. def _timestamp_iso8601(self, value):
  112. if value.microsecond > 0:
  113. timestamp_format = ISO8601_MICRO
  114. else:
  115. timestamp_format = ISO8601
  116. return value.strftime(timestamp_format)
  117. def _timestamp_unixtimestamp(self, value):
  118. return int(calendar.timegm(value.timetuple()))
  119. def _timestamp_rfc822(self, value):
  120. if isinstance(value, datetime.datetime):
  121. value = self._timestamp_unixtimestamp(value)
  122. return formatdate(value, usegmt=True)
  123. def _convert_timestamp_to_str(self, value, timestamp_format=None):
  124. if timestamp_format is None:
  125. timestamp_format = self.TIMESTAMP_FORMAT
  126. timestamp_format = timestamp_format.lower()
  127. datetime_obj = parse_to_aware_datetime(value)
  128. converter = getattr(
  129. self, '_timestamp_%s' % timestamp_format)
  130. final_value = converter(datetime_obj)
  131. return final_value
  132. def _get_serialized_name(self, shape, default_name):
  133. # Returns the serialized name for the shape if it exists.
  134. # Otherwise it will return the passed in default_name.
  135. return shape.serialization.get('name', default_name)
  136. def _get_base64(self, value):
  137. # Returns the base64-encoded version of value, handling
  138. # both strings and bytes. The returned value is a string
  139. # via the default encoding.
  140. if isinstance(value, six.text_type):
  141. value = value.encode(self.DEFAULT_ENCODING)
  142. return base64.b64encode(value).strip().decode(
  143. self.DEFAULT_ENCODING)
  144. def _expand_host_prefix(self, parameters, operation_model):
  145. operation_endpoint = operation_model.endpoint
  146. if operation_endpoint is None:
  147. return None
  148. host_prefix_expression = operation_endpoint['hostPrefix']
  149. input_members = operation_model.input_shape.members
  150. host_labels = [
  151. member for member, shape in input_members.items()
  152. if shape.serialization.get('hostLabel')
  153. ]
  154. format_kwargs = dict((name, parameters[name]) for name in host_labels)
  155. return host_prefix_expression.format(**format_kwargs)
  156. def _prepare_additional_traits(self, request, operation_model):
  157. """Determine if additional traits are required for given model"""
  158. if operation_model.http_checksum_required:
  159. conditionally_calculate_md5(request)
  160. return request
  161. class QuerySerializer(Serializer):
  162. TIMESTAMP_FORMAT = 'iso8601'
  163. def serialize_to_request(self, parameters, operation_model):
  164. shape = operation_model.input_shape
  165. serialized = self._create_default_request()
  166. serialized['method'] = operation_model.http.get('method',
  167. self.DEFAULT_METHOD)
  168. serialized['headers'] = {
  169. 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
  170. }
  171. # The query serializer only deals with body params so
  172. # that's what we hand off the _serialize_* methods.
  173. body_params = self.MAP_TYPE()
  174. body_params['Action'] = operation_model.name
  175. body_params['Version'] = operation_model.metadata['apiVersion']
  176. if shape is not None:
  177. self._serialize(body_params, parameters, shape)
  178. serialized['body'] = body_params
  179. host_prefix = self._expand_host_prefix(parameters, operation_model)
  180. if host_prefix is not None:
  181. serialized['host_prefix'] = host_prefix
  182. serialized = self._prepare_additional_traits(serialized,
  183. operation_model)
  184. return serialized
  185. def _serialize(self, serialized, value, shape, prefix=''):
  186. # serialized: The dict that is incrementally added to with the
  187. # final serialized parameters.
  188. # value: The current user input value.
  189. # shape: The shape object that describes the structure of the
  190. # input.
  191. # prefix: The incrementally built up prefix for the serialized
  192. # key (i.e Foo.bar.members.1).
  193. method = getattr(self, '_serialize_type_%s' % shape.type_name,
  194. self._default_serialize)
  195. method(serialized, value, shape, prefix=prefix)
  196. def _serialize_type_structure(self, serialized, value, shape, prefix=''):
  197. members = shape.members
  198. for key, value in value.items():
  199. member_shape = members[key]
  200. member_prefix = self._get_serialized_name(member_shape, key)
  201. if prefix:
  202. member_prefix = '%s.%s' % (prefix, member_prefix)
  203. self._serialize(serialized, value, member_shape, member_prefix)
  204. def _serialize_type_list(self, serialized, value, shape, prefix=''):
  205. if not value:
  206. # The query protocol serializes empty lists.
  207. serialized[prefix] = ''
  208. return
  209. if self._is_shape_flattened(shape):
  210. list_prefix = prefix
  211. if shape.member.serialization.get('name'):
  212. name = self._get_serialized_name(shape.member, default_name='')
  213. # Replace '.Original' with '.{name}'.
  214. list_prefix = '.'.join(prefix.split('.')[:-1] + [name])
  215. else:
  216. list_name = shape.member.serialization.get('name', 'member')
  217. list_prefix = '%s.%s' % (prefix, list_name)
  218. for i, element in enumerate(value, 1):
  219. element_prefix = '%s.%s' % (list_prefix, i)
  220. element_shape = shape.member
  221. self._serialize(serialized, element, element_shape, element_prefix)
  222. def _serialize_type_map(self, serialized, value, shape, prefix=''):
  223. if self._is_shape_flattened(shape):
  224. full_prefix = prefix
  225. else:
  226. full_prefix = '%s.entry' % prefix
  227. template = full_prefix + '.{i}.{suffix}'
  228. key_shape = shape.key
  229. value_shape = shape.value
  230. key_suffix = self._get_serialized_name(key_shape, default_name='key')
  231. value_suffix = self._get_serialized_name(value_shape, 'value')
  232. for i, key in enumerate(value, 1):
  233. key_prefix = template.format(i=i, suffix=key_suffix)
  234. value_prefix = template.format(i=i, suffix=value_suffix)
  235. self._serialize(serialized, key, key_shape, key_prefix)
  236. self._serialize(serialized, value[key], value_shape, value_prefix)
  237. def _serialize_type_blob(self, serialized, value, shape, prefix=''):
  238. # Blob args must be base64 encoded.
  239. serialized[prefix] = self._get_base64(value)
  240. def _serialize_type_timestamp(self, serialized, value, shape, prefix=''):
  241. serialized[prefix] = self._convert_timestamp_to_str(
  242. value, shape.serialization.get('timestampFormat'))
  243. def _serialize_type_boolean(self, serialized, value, shape, prefix=''):
  244. if value:
  245. serialized[prefix] = 'true'
  246. else:
  247. serialized[prefix] = 'false'
  248. def _default_serialize(self, serialized, value, shape, prefix=''):
  249. serialized[prefix] = value
  250. def _is_shape_flattened(self, shape):
  251. return shape.serialization.get('flattened')
  252. class EC2Serializer(QuerySerializer):
  253. """EC2 specific customizations to the query protocol serializers.
  254. The EC2 model is almost, but not exactly, similar to the query protocol
  255. serializer. This class encapsulates those differences. The model
  256. will have be marked with a ``protocol`` of ``ec2``, so you don't need
  257. to worry about wiring this class up correctly.
  258. """
  259. def _get_serialized_name(self, shape, default_name):
  260. # Returns the serialized name for the shape if it exists.
  261. # Otherwise it will return the passed in default_name.
  262. if 'queryName' in shape.serialization:
  263. return shape.serialization['queryName']
  264. elif 'name' in shape.serialization:
  265. # A locationName is always capitalized
  266. # on input for the ec2 protocol.
  267. name = shape.serialization['name']
  268. return name[0].upper() + name[1:]
  269. else:
  270. return default_name
  271. def _serialize_type_list(self, serialized, value, shape, prefix=''):
  272. for i, element in enumerate(value, 1):
  273. element_prefix = '%s.%s' % (prefix, i)
  274. element_shape = shape.member
  275. self._serialize(serialized, element, element_shape, element_prefix)
  276. class JSONSerializer(Serializer):
  277. TIMESTAMP_FORMAT = 'unixtimestamp'
  278. def serialize_to_request(self, parameters, operation_model):
  279. target = '%s.%s' % (operation_model.metadata['targetPrefix'],
  280. operation_model.name)
  281. json_version = operation_model.metadata['jsonVersion']
  282. serialized = self._create_default_request()
  283. serialized['method'] = operation_model.http.get('method',
  284. self.DEFAULT_METHOD)
  285. serialized['headers'] = {
  286. 'X-Amz-Target': target,
  287. 'Content-Type': 'application/x-amz-json-%s' % json_version,
  288. }
  289. body = self.MAP_TYPE()
  290. input_shape = operation_model.input_shape
  291. if input_shape is not None:
  292. self._serialize(body, parameters, input_shape)
  293. serialized['body'] = json.dumps(body).encode(self.DEFAULT_ENCODING)
  294. host_prefix = self._expand_host_prefix(parameters, operation_model)
  295. if host_prefix is not None:
  296. serialized['host_prefix'] = host_prefix
  297. serialized = self._prepare_additional_traits(serialized,
  298. operation_model)
  299. return serialized
  300. def _serialize(self, serialized, value, shape, key=None):
  301. method = getattr(self, '_serialize_type_%s' % shape.type_name,
  302. self._default_serialize)
  303. method(serialized, value, shape, key)
  304. def _serialize_type_structure(self, serialized, value, shape, key):
  305. if shape.is_document_type:
  306. serialized[key] = value
  307. else:
  308. if key is not None:
  309. # If a key is provided, this is a result of a recursive
  310. # call so we need to add a new child dict as the value
  311. # of the passed in serialized dict. We'll then add
  312. # all the structure members as key/vals in the new serialized
  313. # dictionary we just created.
  314. new_serialized = self.MAP_TYPE()
  315. serialized[key] = new_serialized
  316. serialized = new_serialized
  317. members = shape.members
  318. for member_key, member_value in value.items():
  319. member_shape = members[member_key]
  320. if 'name' in member_shape.serialization:
  321. member_key = member_shape.serialization['name']
  322. self._serialize(serialized, member_value, member_shape, member_key)
  323. def _serialize_type_map(self, serialized, value, shape, key):
  324. map_obj = self.MAP_TYPE()
  325. serialized[key] = map_obj
  326. for sub_key, sub_value in value.items():
  327. self._serialize(map_obj, sub_value, shape.value, sub_key)
  328. def _serialize_type_list(self, serialized, value, shape, key):
  329. list_obj = []
  330. serialized[key] = list_obj
  331. for list_item in value:
  332. wrapper = {}
  333. # The JSON list serialization is the only case where we aren't
  334. # setting a key on a dict. We handle this by using
  335. # a __current__ key on a wrapper dict to serialize each
  336. # list item before appending it to the serialized list.
  337. self._serialize(wrapper, list_item, shape.member, "__current__")
  338. list_obj.append(wrapper["__current__"])
  339. def _default_serialize(self, serialized, value, shape, key):
  340. serialized[key] = value
  341. def _serialize_type_timestamp(self, serialized, value, shape, key):
  342. serialized[key] = self._convert_timestamp_to_str(
  343. value, shape.serialization.get('timestampFormat'))
  344. def _serialize_type_blob(self, serialized, value, shape, key):
  345. serialized[key] = self._get_base64(value)
  346. class BaseRestSerializer(Serializer):
  347. """Base class for rest protocols.
  348. The only variance between the various rest protocols is the
  349. way that the body is serialized. All other aspects (headers, uri, etc.)
  350. are the same and logic for serializing those aspects lives here.
  351. Subclasses must implement the ``_serialize_body_params`` method.
  352. """
  353. QUERY_STRING_TIMESTAMP_FORMAT = 'iso8601'
  354. HEADER_TIMESTAMP_FORMAT = 'rfc822'
  355. # This is a list of known values for the "location" key in the
  356. # serialization dict. The location key tells us where on the request
  357. # to put the serialized value.
  358. KNOWN_LOCATIONS = ['uri', 'querystring', 'header', 'headers']
  359. def serialize_to_request(self, parameters, operation_model):
  360. serialized = self._create_default_request()
  361. serialized['method'] = operation_model.http.get('method',
  362. self.DEFAULT_METHOD)
  363. shape = operation_model.input_shape
  364. if shape is None:
  365. serialized['url_path'] = operation_model.http['requestUri']
  366. return serialized
  367. shape_members = shape.members
  368. # While the ``serialized`` key holds the final serialized request
  369. # data, we need interim dicts for the various locations of the
  370. # request. We need this for the uri_path_kwargs and the
  371. # query_string_kwargs because they are templated, so we need
  372. # to gather all the needed data for the string template,
  373. # then we render the template. The body_kwargs is needed
  374. # because once we've collected them all, we run them through
  375. # _serialize_body_params, which for rest-json, creates JSON,
  376. # and for rest-xml, will create XML. This is what the
  377. # ``partitioned`` dict below is for.
  378. partitioned = {
  379. 'uri_path_kwargs': self.MAP_TYPE(),
  380. 'query_string_kwargs': self.MAP_TYPE(),
  381. 'body_kwargs': self.MAP_TYPE(),
  382. 'headers': self.MAP_TYPE(),
  383. }
  384. for param_name, param_value in parameters.items():
  385. if param_value is None:
  386. # Don't serialize any parameter with a None value.
  387. continue
  388. self._partition_parameters(partitioned, param_name, param_value,
  389. shape_members)
  390. serialized['url_path'] = self._render_uri_template(
  391. operation_model.http['requestUri'],
  392. partitioned['uri_path_kwargs'])
  393. # Note that we lean on the http implementation to handle the case
  394. # where the requestUri path already has query parameters.
  395. # The bundled http client, requests, already supports this.
  396. serialized['query_string'] = partitioned['query_string_kwargs']
  397. if partitioned['headers']:
  398. serialized['headers'] = partitioned['headers']
  399. self._serialize_payload(partitioned, parameters,
  400. serialized, shape, shape_members)
  401. host_prefix = self._expand_host_prefix(parameters, operation_model)
  402. if host_prefix is not None:
  403. serialized['host_prefix'] = host_prefix
  404. serialized = self._prepare_additional_traits(serialized,
  405. operation_model)
  406. return serialized
  407. def _render_uri_template(self, uri_template, params):
  408. # We need to handle two cases::
  409. #
  410. # /{Bucket}/foo
  411. # /{Key+}/bar
  412. # A label ending with '+' is greedy. There can only
  413. # be one greedy key.
  414. encoded_params = {}
  415. for template_param in re.findall(r'{(.*?)}', uri_template):
  416. if template_param.endswith('+'):
  417. encoded_params[template_param] = percent_encode(
  418. params[template_param[:-1]], safe='/~')
  419. else:
  420. encoded_params[template_param] = percent_encode(
  421. params[template_param])
  422. return uri_template.format(**encoded_params)
  423. def _serialize_payload(self, partitioned, parameters,
  424. serialized, shape, shape_members):
  425. # partitioned - The user input params partitioned by location.
  426. # parameters - The user input params.
  427. # serialized - The final serialized request dict.
  428. # shape - Describes the expected input shape
  429. # shape_members - The members of the input struct shape
  430. payload_member = shape.serialization.get('payload')
  431. if payload_member is not None and \
  432. shape_members[payload_member].type_name in ['blob', 'string']:
  433. # If it's streaming, then the body is just the
  434. # value of the payload.
  435. body_payload = parameters.get(payload_member, b'')
  436. body_payload = self._encode_payload(body_payload)
  437. serialized['body'] = body_payload
  438. elif payload_member is not None:
  439. # If there's a payload member, we serialized that
  440. # member to they body.
  441. body_params = parameters.get(payload_member)
  442. if body_params is not None:
  443. serialized['body'] = self._serialize_body_params(
  444. body_params,
  445. shape_members[payload_member])
  446. elif partitioned['body_kwargs']:
  447. serialized['body'] = self._serialize_body_params(
  448. partitioned['body_kwargs'], shape)
  449. def _encode_payload(self, body):
  450. if isinstance(body, six.text_type):
  451. return body.encode(self.DEFAULT_ENCODING)
  452. return body
  453. def _partition_parameters(self, partitioned, param_name,
  454. param_value, shape_members):
  455. # This takes the user provided input parameter (``param``)
  456. # and figures out where they go in the request dict.
  457. # Some params are HTTP headers, some are used in the URI, some
  458. # are in the request body. This method deals with this.
  459. member = shape_members[param_name]
  460. location = member.serialization.get('location')
  461. key_name = member.serialization.get('name', param_name)
  462. if location == 'uri':
  463. partitioned['uri_path_kwargs'][key_name] = param_value
  464. elif location == 'querystring':
  465. if isinstance(param_value, dict):
  466. partitioned['query_string_kwargs'].update(param_value)
  467. elif isinstance(param_value, bool):
  468. partitioned['query_string_kwargs'][
  469. key_name] = str(param_value).lower()
  470. elif member.type_name == 'timestamp':
  471. timestamp_format = member.serialization.get(
  472. 'timestampFormat', self.QUERY_STRING_TIMESTAMP_FORMAT)
  473. partitioned['query_string_kwargs'][
  474. key_name] = self._convert_timestamp_to_str(
  475. param_value, timestamp_format
  476. )
  477. else:
  478. partitioned['query_string_kwargs'][key_name] = param_value
  479. elif location == 'header':
  480. shape = shape_members[param_name]
  481. value = self._convert_header_value(shape, param_value)
  482. partitioned['headers'][key_name] = str(value)
  483. elif location == 'headers':
  484. # 'headers' is a bit of an oddball. The ``key_name``
  485. # is actually really a prefix for the header names:
  486. header_prefix = key_name
  487. # The value provided by the user is a dict so we'll be
  488. # creating multiple header key/val pairs. The key
  489. # name to use for each header is the header_prefix (``key_name``)
  490. # plus the key provided by the user.
  491. self._do_serialize_header_map(header_prefix,
  492. partitioned['headers'],
  493. param_value)
  494. else:
  495. partitioned['body_kwargs'][param_name] = param_value
  496. def _do_serialize_header_map(self, header_prefix, headers, user_input):
  497. for key, val in user_input.items():
  498. full_key = header_prefix + key
  499. headers[full_key] = val
  500. def _serialize_body_params(self, params, shape):
  501. raise NotImplementedError('_serialize_body_params')
  502. def _convert_header_value(self, shape, value):
  503. if shape.type_name == 'timestamp':
  504. datetime_obj = parse_to_aware_datetime(value)
  505. timestamp = calendar.timegm(datetime_obj.utctimetuple())
  506. timestamp_format = shape.serialization.get(
  507. 'timestampFormat', self.HEADER_TIMESTAMP_FORMAT)
  508. return self._convert_timestamp_to_str(timestamp, timestamp_format)
  509. elif is_json_value_header(shape):
  510. # Serialize with no spaces after separators to save space in
  511. # the header.
  512. return self._get_base64(json.dumps(value, separators=(',', ':')))
  513. else:
  514. return value
  515. class RestJSONSerializer(BaseRestSerializer, JSONSerializer):
  516. def _serialize_body_params(self, params, shape):
  517. serialized_body = self.MAP_TYPE()
  518. self._serialize(serialized_body, params, shape)
  519. return json.dumps(serialized_body).encode(self.DEFAULT_ENCODING)
  520. class RestXMLSerializer(BaseRestSerializer):
  521. TIMESTAMP_FORMAT = 'iso8601'
  522. def _serialize_body_params(self, params, shape):
  523. root_name = shape.serialization['name']
  524. pseudo_root = ElementTree.Element('')
  525. self._serialize(shape, params, pseudo_root, root_name)
  526. real_root = list(pseudo_root)[0]
  527. return ElementTree.tostring(real_root, encoding=self.DEFAULT_ENCODING)
  528. def _serialize(self, shape, params, xmlnode, name):
  529. method = getattr(self, '_serialize_type_%s' % shape.type_name,
  530. self._default_serialize)
  531. method(xmlnode, params, shape, name)
  532. def _serialize_type_structure(self, xmlnode, params, shape, name):
  533. structure_node = ElementTree.SubElement(xmlnode, name)
  534. if 'xmlNamespace' in shape.serialization:
  535. namespace_metadata = shape.serialization['xmlNamespace']
  536. attribute_name = 'xmlns'
  537. if namespace_metadata.get('prefix'):
  538. attribute_name += ':%s' % namespace_metadata['prefix']
  539. structure_node.attrib[attribute_name] = namespace_metadata['uri']
  540. for key, value in params.items():
  541. member_shape = shape.members[key]
  542. member_name = member_shape.serialization.get('name', key)
  543. # We need to special case member shapes that are marked as an
  544. # xmlAttribute. Rather than serializing into an XML child node,
  545. # we instead serialize the shape to an XML attribute of the
  546. # *current* node.
  547. if value is None:
  548. # Don't serialize any param whose value is None.
  549. return
  550. if member_shape.serialization.get('xmlAttribute'):
  551. # xmlAttributes must have a serialization name.
  552. xml_attribute_name = member_shape.serialization['name']
  553. structure_node.attrib[xml_attribute_name] = value
  554. continue
  555. self._serialize(member_shape, value, structure_node, member_name)
  556. def _serialize_type_list(self, xmlnode, params, shape, name):
  557. member_shape = shape.member
  558. if shape.serialization.get('flattened'):
  559. element_name = name
  560. list_node = xmlnode
  561. else:
  562. element_name = member_shape.serialization.get('name', 'member')
  563. list_node = ElementTree.SubElement(xmlnode, name)
  564. for item in params:
  565. self._serialize(member_shape, item, list_node, element_name)
  566. def _serialize_type_map(self, xmlnode, params, shape, name):
  567. # Given the ``name`` of MyMap, and input of {"key1": "val1"}
  568. # we serialize this as:
  569. # <MyMap>
  570. # <entry>
  571. # <key>key1</key>
  572. # <value>val1</value>
  573. # </entry>
  574. # </MyMap>
  575. node = ElementTree.SubElement(xmlnode, name)
  576. # TODO: handle flattened maps.
  577. for key, value in params.items():
  578. entry_node = ElementTree.SubElement(node, 'entry')
  579. key_name = self._get_serialized_name(shape.key, default_name='key')
  580. val_name = self._get_serialized_name(shape.value,
  581. default_name='value')
  582. self._serialize(shape.key, key, entry_node, key_name)
  583. self._serialize(shape.value, value, entry_node, val_name)
  584. def _serialize_type_boolean(self, xmlnode, params, shape, name):
  585. # For scalar types, the 'params' attr is actually just a scalar
  586. # value representing the data we need to serialize as a boolean.
  587. # It will either be 'true' or 'false'
  588. node = ElementTree.SubElement(xmlnode, name)
  589. if params:
  590. str_value = 'true'
  591. else:
  592. str_value = 'false'
  593. node.text = str_value
  594. def _serialize_type_blob(self, xmlnode, params, shape, name):
  595. node = ElementTree.SubElement(xmlnode, name)
  596. node.text = self._get_base64(params)
  597. def _serialize_type_timestamp(self, xmlnode, params, shape, name):
  598. node = ElementTree.SubElement(xmlnode, name)
  599. node.text = self._convert_timestamp_to_str(
  600. params, shape.serialization.get('timestampFormat'))
  601. def _default_serialize(self, xmlnode, params, shape, name):
  602. node = ElementTree.SubElement(xmlnode, name)
  603. node.text = six.text_type(params)
  604. SERIALIZERS = {
  605. 'ec2': EC2Serializer,
  606. 'query': QuerySerializer,
  607. 'json': JSONSerializer,
  608. 'rest-json': RestJSONSerializer,
  609. 'rest-xml': RestXMLSerializer,
  610. }