Пример #1
0
    def get_regular_properties(self, _type, *args, **kwargs):
        """Make table with properties by schema_id
        :param str _type:
        :rtype: str
        """
        if not SchemaObjects.contains(_type):
            return _type
        schema = SchemaObjects.get(_type)
        if schema.schema_type == SchemaTypes.DEFINITION and not kwargs.get('definition'):
            return ''
        head = """.. csv-table::
    :delim: |
    :header: "Name", "Required", "Type", "Format", "Properties", "Description"
    :widths: 20, 10, 15, 15, 30, 25

"""
        body = []
        if schema.properties:
            for p in schema.properties:
                body.append('        {} | {} | {} | {} | {} | {}'.format(
                    p.get('name') or '',
                    'Yes' if p.get('required') else 'No',
                    self.get_type_description(p['type'], *args, **kwargs),
                    p.get('type_format') or '',
                    '{}'.format(p.get('type_properties') or ''),
                    p.get('description') or '')
                )
            body.sort()
        return (head + '\n'.join(body))
Пример #2
0
    def get_additional_properties(self, _type, *args, **kwargs):
        """Make head and table with additional properties by schema_id
        :param str _type:
        :rtype: str
        """
        if not SchemaObjects.contains(_type):
            return _type
        schema = SchemaObjects.get(_type)
        body = []
        for sch in schema.nested_schemas:  # complex types
            nested_schema = SchemaObjects.get(sch)
            if not (nested_schema or isinstance(nested_schema, SchemaMapWrapper)):
                continue

            body.append('Map of {{"key":"{}"}}\n\n'.format(self.get_type_description(
                nested_schema.schema_id, *args, **kwargs))  # head
            )
            if nested_schema.is_array:  # table
                _schema = SchemaObjects.get(nested_schema.item.get('type'))
                if _schema and _schema.schema_type == SchemaTypes.INLINE:
                    body.append(self.get_regular_properties(_schema.schema_id, *args, **kwargs))
            else:
                body.append(self.get_regular_properties(nested_schema.schema_id, *args, **kwargs))
        if schema.type_format:  # basic types, only head
            body.append(
                'Map of {{"key":"{}"}}'.format(self.get_type_description(schema.type_format, *args, **kwargs)))
        return ''.join(body)
Пример #3
0
    def get_property_example(cls, property_, nested=None, **kw):
        """ Get example for property

        :param dict property_:
        :param set nested:
        :return: example value
        """
        paths = kw.get('paths', [])
        name = kw.get('name', '')
        result = None
        if name and paths:
            paths = list(map(lambda path: '.'.join((path, name)), paths))
            result, path = cls._get_custom_example(paths)
            if result is not None and property_['type'] in PRIMITIVE_TYPES:
                cls._example_validate(
                    path, result, property_['type'], property_['type_format'])
                return result

        if SchemaObjects.contains(property_['type']):
            schema = SchemaObjects.get(property_['type'])
            if result is not None:
                if schema.is_array:
                    if not isinstance(result, list):
                        result = [result] * cls.EXAMPLE_ARRAY_ITEMS_COUNT
                else:
                    if isinstance(result, list):
                        cls.logger.warning(
                            'Example type mismatch in path {}'.format(schema.ref_path))
            else:
                result = cls.get_example_by_schema(schema, **kw)

            if (not result) and schema.nested_schemas:
                for _schema_id in schema.nested_schemas:
                    _schema = SchemaObjects.get(_schema_id)
                    if _schema:
                        if isinstance(_schema, SchemaMapWrapper):
                            result[_schema.name] = cls.get_example_by_schema(_schema, **kw)
                        elif _schema.nested_schemas:
                            for _schema__id in _schema.nested_schemas:
                                _schema_ = SchemaObjects.get(_schema__id)
                                if isinstance(_schema_, SchemaMapWrapper):
                                    result[_schema.name] = cls.get_example_by_schema(_schema_, **kw)
        else:
            result = cls.get_example_value_for_primitive_type(
                property_['type'],
                property_['type_properties'],
                property_['type_format'],
                **kw
            )
        return result
Пример #4
0
 def get_type_description(self, _type, suffix='', *args, **kwargs):
     """ Get description of type
     :param suffix:
     :param str _type:
     :rtype: str
     """
     if not SchemaObjects.contains(_type):
         return _type
     schema = SchemaObjects.get(_type)
     if schema.all_of:
         models = ','.join(
             (self.get_type_description(_type, *args, **kwargs) for _type in schema.all_of)
         )
         result = '{}'.format(models.split(',')[0])
         for r in models.split(',')[1:]:
             result += ' extended {}'.format(r)
     elif schema.is_array:
         result = 'array of {}'.format(
             self.get_type_description(schema.item['type'], *args, **kwargs))
     else:
         result = ':ref:`{} <{}{}>`'.format(schema.name, schema.schema_id, suffix)
     return result
Пример #5
0
    def get_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name=''):
        """ Get example by schema object

        :param Schema schema: current schema
        :param list ignored_schemas: list of previous schemas
            for avoid circular references
        :param list paths: list object paths (ex. #/definitions/Model.property)
            If nested schemas exists, custom examples checks in order from paths
        :param str name: name of property schema object if exists
        :return: dict or list (if schema is array)
        """
        if schema.schema_example:
            return schema.schema_example

        if ignored_schemas is None:
            ignored_schemas = []

        if paths is None:
            paths = []

        if name:
            paths = list(map(lambda path: '.'.join((path, name)), paths))

        if schema.ref_path:
            paths.append(schema.ref_path)

        if schema.schema_id in ignored_schemas:
            result = [] if schema.is_array else {}
        else:
            schemas = ignored_schemas + [schema.schema_id]
            kwargs = dict(
                ignored_schemas=schemas,
                paths=paths
            )
            if schema.is_array:
                result = cls.get_example_for_array(
                    schema.item, **kwargs)
            elif schema.type in PRIMITIVE_TYPES:
                result = cls.get_example_value_for_primitive_type(
                    schema.type, schema.raw, schema.type_format, paths=paths
                )
            elif schema.all_of:
                result = {}
                for _schema_id in schema.all_of:
                    schema = SchemaObjects.get(_schema_id)
                    result.update(cls.get_example_by_schema(schema, **kwargs))
            else:
                result = cls.get_example_for_object(
                    schema.properties, nested=schema.nested_schemas, **kwargs)
        return result
Пример #6
0
    def get_response_example(cls, operation, response):
        """ Get example for response object by operation object

        :param Operation operation: operation object
        :param Response response: response object
        """
        path = "#/paths/'{}'/{}/responses/{}".format(
            operation.path, operation.method, response.name)
        kwargs = dict(paths=[path])

        if response.type in PRIMITIVE_TYPES:
            result = cls.get_example_value_for_primitive_type(
                response.type, response.properties, response.type_format, **kwargs)
        else:
            schema = SchemaObjects.get(response.type)
            result = cls.get_example_by_schema(schema, **kwargs)

        return result
Пример #7
0
    def sorted(collection):
        """
        sorting dict by key,
        schema-collection by schema-name
        operations by id
        """
        if len(collection) < 1:
            return collection

        if isinstance(collection, dict):
            return sorted(collection.items(), key=lambda x: x[0])

        if isinstance(list(collection)[0], Operation):
            key = lambda x: x.operation_id
        elif isinstance(list(collection)[0], str):
            key = lambda x: SchemaObjects.get(x).name
        else:
            raise TypeError(type(collection[0]))
        return sorted(collection, key=key)