utils.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Copyright 2015 ksyun.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://www.apache.org/licenses/LICENSE-2.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. from collections import namedtuple
  14. def py_type_name(type_name):
  15. """Get the Python type name for a given model type.
  16. >>> py_type_name('list')
  17. 'list'
  18. >>> py_type_name('structure')
  19. 'dict'
  20. :rtype: string
  21. """
  22. return {
  23. 'blob': 'bytes',
  24. 'character': 'string',
  25. 'double': 'float',
  26. 'long': 'integer',
  27. 'map': 'dict',
  28. 'structure': 'dict',
  29. 'timestamp': 'datetime',
  30. }.get(type_name, type_name)
  31. def py_default(type_name):
  32. """Get the Python default value for a given model type.
  33. >>> py_default('string')
  34. '\'string\''
  35. >>> py_default('list')
  36. '[...]'
  37. >>> py_default('unknown')
  38. '...'
  39. :rtype: string
  40. """
  41. return {
  42. 'double': '123.0',
  43. 'long': '123',
  44. 'integer': '123',
  45. 'string': "'string'",
  46. 'blob': "b'bytes'",
  47. 'boolean': 'True|False',
  48. 'list': '[...]',
  49. 'map': '{...}',
  50. 'structure': '{...}',
  51. 'timestamp': 'datetime(2015, 1, 1)',
  52. }.get(type_name, '...')
  53. def get_official_service_name(service_model):
  54. """Generate the official name of an KSYUN Service
  55. :param service_model: The service model representing the service
  56. """
  57. official_name = service_model.metadata.get('serviceFullName')
  58. short_name = service_model.metadata.get('serviceAbbreviation', '')
  59. if short_name.startswith('Amazon'):
  60. short_name = short_name[7:]
  61. if short_name.startswith('AWS'):
  62. short_name = short_name[4:]
  63. if short_name and short_name.lower() not in official_name.lower():
  64. official_name += ' ({0})'.format(short_name)
  65. return official_name
  66. _DocumentedShape = namedtuple(
  67. 'DocumentedShape', ['name', 'type_name', 'documentation', 'metadata',
  68. 'members', 'required_members'])
  69. class DocumentedShape (_DocumentedShape):
  70. """Use this class to inject new shapes into a model for documentation"""
  71. def __new__(cls, name, type_name, documentation, metadata=None,
  72. members=None, required_members=None):
  73. if metadata is None:
  74. metadata = []
  75. if members is None:
  76. members = []
  77. if required_members is None:
  78. required_members = []
  79. return super(DocumentedShape, cls).__new__(
  80. cls, name, type_name, documentation, metadata, members,
  81. required_members)
  82. class AutoPopulatedParam(object):
  83. def __init__(self, name, param_description=None):
  84. self.name = name
  85. self.param_description = param_description
  86. if param_description is None:
  87. self.param_description = (
  88. 'Please note that this parameter is automatically populated '
  89. 'if it is not provided. Including this parameter is not '
  90. 'required\n')
  91. def document_auto_populated_param(self, event_name, section, **kwargs):
  92. """Documents auto populated parameters
  93. It will remove any required marks for the parameter, remove the
  94. parameter from the example, and add a snippet about the parameter
  95. being autopopulated in the description.
  96. """
  97. if event_name.startswith('docs.request-params'):
  98. if self.name in section.available_sections:
  99. section = section.get_section(self.name)
  100. if 'is-required' in section.available_sections:
  101. section.delete_section('is-required')
  102. description_section = section.get_section(
  103. 'param-documentation')
  104. description_section.writeln(self.param_description)
  105. elif event_name.startswith('docs.request-example'):
  106. section = section.get_section('structure-value')
  107. if self.name in section.available_sections:
  108. section.delete_section(self.name)
  109. class HideParamFromOperations(object):
  110. """Hides a single parameter from multiple operations.
  111. This method will remove a parameter from documentation and from
  112. examples. This method is typically used for things that are
  113. automatically populated because a user would be unable to provide
  114. a value (e.g., a checksum of a serialized XML request body)."""
  115. def __init__(self, service_name, parameter_name, operation_names):
  116. """
  117. :type service_name: str
  118. :param service_name: Name of the service to modify.
  119. :type parameter_name: str
  120. :param parameter_name: Name of the parameter to modify.
  121. :type operation_names: list
  122. :param operation_names: Operation names to modify.
  123. """
  124. self._parameter_name = parameter_name
  125. self._params_events = set()
  126. self._example_events = set()
  127. # Build up the sets of relevant event names.
  128. param_template = 'docs.request-params.%s.%s.complete-section'
  129. example_template = 'docs.request-example.%s.%s.complete-section'
  130. for name in operation_names:
  131. self._params_events.add(param_template % (service_name, name))
  132. self._example_events.add(example_template % (service_name, name))
  133. def hide_param(self, event_name, section, **kwargs):
  134. if event_name in self._example_events:
  135. # Modify the structure value for example events.
  136. section = section.get_section('structure-value')
  137. elif event_name not in self._params_events:
  138. return
  139. if self._parameter_name in section.available_sections:
  140. section.delete_section(self._parameter_name)
  141. class AppendParamDocumentation(object):
  142. """Appends documentation to a specific parameter"""
  143. def __init__(self, parameter_name, doc_string):
  144. self._parameter_name = parameter_name
  145. self._doc_string = doc_string
  146. def append_documentation(self, event_name, section, **kwargs):
  147. if self._parameter_name in section.available_sections:
  148. section = section.get_section(self._parameter_name)
  149. description_section = section.get_section(
  150. 'param-documentation')
  151. description_section.writeln(self._doc_string)