Generate definitions to be converted to swagger schema.
354096
def iter_definitions(definitions, operations):
    
    # general error schema per errors.py
    for error_schema_class in [ErrorSchema, ErrorContextSchema, SubErrorSchema]:
        yield error_schema_class()

    # add all request and response schemas
    for operation, obj, rule, func in operations:
        yield get_request_schema(func)
        yield get_response_schema(func)
1138612
def generate_stub(self):
        
        needed_types = self.required_types - BUILTIN_TYPES

        needed_types -= self.defined_types
        _logger.debug("defined types: %s", self.defined_types)

        module_vars = {v.name for v in self.root.variables}
        _logger.debug("module variables: %s", module_vars)

        qualified_types = {n for n in needed_types if "." in n}
        qualified_namespaces = {".".join(n.split(".")[:-1]) for n in qualified_types}

        needed_namespaces = qualified_namespaces - module_vars
        needed_types -= qualified_types
        _logger.debug("needed namespaces: %s", needed_namespaces)

        imported_names = {n.split("::")[0] for n in self.imported_names}
        imported_types = imported_names & (needed_types | needed_namespaces)
        needed_types -= imported_types
        needed_namespaces -= imported_names
        _logger.debug("used imported types: %s", imported_types)

        try:
            typing_mod = __import__("typing")
            typing_types = {n for n in needed_types if hasattr(typing_mod, n)}
            needed_types -= typing_types
            _logger.debug("types from typing module: %s", typing_types)
        except ImportError:
            typing_types = set()
            _logger.warn("typing module not installed")

        if len(needed_types) > 0:
            raise ValueError("Unknown types: " + ", ".join(needed_types))

        out = StringIO()
        started = False

        if len(typing_types) > 0:
            line = self.generate_import_from("typing", typing_types)
            out.write(line + "\n")
            started = True

        if len(imported_types) > 0:
            if started:
                out.write("\n")
            # preserve the import order in the source file
            for name in self.imported_names:
                if name.split("::")[0] in imported_types:
                    line = self.generate_import_from(self.imported_names[name], {name})
                    out.write(line + "\n")
            started = True

        if len(needed_namespaces) > 0:
            if started:
                out.write("\n")
            as_names = {n.split("::")[0]: n for n in self.imported_namespaces if "::" in n}
            for module_ in sorted(needed_namespaces):
                if module_ in as_names:
                    a, n = as_names[module_].split("::")
                    out.write("import " + n + " as " + a + "\n")
                else:
                    out.write("import " + module_ + "\n")
            started = True

        if len(self.aliases) > 0:
            if started:
                out.write("\n")
            for alias, signature in self.aliases.items():
                out.write("%s = %s\n" % (alias, signature))
            started = True

        if started:
            out.write("\n")
        stub_lines = self.root.get_code()
        n_lines = len(stub_lines)
        for line_no in range(n_lines):
            prev_line = stub_lines[line_no - 1] if line_no > 0 else None
            line = stub_lines[line_no]
            next_line = stub_lines[line_no + 1] if line_no < (n_lines - 1) else None
            if (
                line.startswith("class ")
                and (prev_line is not None)
                and (
                    (not prev_line.startswith("class "))
                    or (next_line and next_line.startswith(" "))
                )
            ):
                out.write("\n")
            if (
                line.startswith("def ")
                and (prev_line is not None)
                and (prev_line.startswith((" ", "class ")))
            ):
                out.write("\n")
            out.write(line + "\n")
            line_no += 1
        return out.getvalue()
229359
def add_definitions(definitions, operations):
    
    for definition_schema in iter_definitions(definitions, operations):
        if definition_schema is None:
            continue
        if isinstance(definition_schema, str):
            continue

        for name, schema in iter_schemas(definition_schema):
            definitions.setdefault(name, swagger.Schema(schema))
1156908
def build_schema(
    source: Union[str, Source],
    assume_valid=False,
    assume_valid_sdl=False,
    no_location=False,
    experimental_fragment_variables=False,
) -> GraphQLSchema:
    """"""
    return build_ast_schema(
        parse(
            source,
            no_location=no_location,
            experimental_fragment_variables=experimental_fragment_variables,
        ),
        assume_valid=assume_valid,
        assume_valid_sdl=assume_valid_sdl,
    )
637659
def generate(self, more_content=None, all_members=False):
        # type: (Any, str, bool, bool) -> None
        
        directive = getattr(self, 'directivetype', self.objtype)

        # parse components out of name
        (file, _, namepath) = self.name.rpartition(':')
        (contract_name, _, fullname) = namepath.partition('.')
        (name, _, paramtypes) = fullname.partition('(')

        # normalize components
        name = name.strip() or None

        if directive in ('contract', 'interface', 'library') and name is None:
            name = contract_name
            contract_name = None

        paramtypes = ','.join(ptype.strip() for ptype in paramtypes.split(','))
        paramtypes = re.sub(r'\s+', ' ', paramtypes)
        if paramtypes.endswith(')'):
            paramtypes = paramtypes[:-1]

        # build query
        expressions = [
            SolidityObject.objtype == directive,
            SolidityObject.name == name,
        ]

        if file:
            expressions.append(SolidityObject.file == file)
        if contract_name:
            expressions.append(SolidityObject.contract_name == contract_name)
        if paramtypes:
            expressions.append(SolidityObject.paramtypes == paramtypes)

        # get associated object
        query = SolidityObject.select().where(*expressions)
        sol_objects = tuple(query)
        if len(sol_objects) == 0:
            logger.warning('{} {} could not be found via query:\n{}'.format(
                directive, self.name, ',\n'.join(
                    '  ' + str(expr.lhs.column_name) +
                    str(expr.op) + ('' if expr.rhs is None else expr.rhs)
                    for expr in expressions
                )))
            return
        elif len(sol_objects) > 1:
            logger.warning('multiple candidates for {} {} found:\n{}'.format(
                directive, self.name,
                '\n'.join('  ' + obj.signature for obj in sol_objects)))

        self.object = sol_objects[0]

        # begin rendering output
        sourcename = self.get_sourcename()

        # make sure that the result starts with an empty line.  This is
        # necessary for some situations where another directive preprocesses
        # reST and no starting newline is present
        self.add_line('', sourcename)

        # generate the directive header and options, if applicable
        self.add_directive_header()

        # make sure content is indented
        # TODO: consider adding a source unit directive
        self.indent += self.content_indent

        # add all content (from docstrings, attribute docs etc.)
        self.add_content(more_content)

        # document members, if possible
        if directive in ('contract', 'interface', 'library'):
            self.add_line('', sourcename)
            self.document_members(all_members)
37830
function Mongo_schema(definition, options) {

        if (!options) {
            options = {};
        }
        if (!Type.assert(Type.OBJECT, options)) {
            throw new error.HttpError(500, {options: options}, 'Schema options must be object');
        } else if (!Type.assert(Type.OBJECT, definition)) {
            throw new error.HttpError(500, {definition: definition}, 'Schema definition must be object');
        }
        logger.info('Mongo.schema:', {
            definition: definition,
            options: options
        });
        return new mongoose.Schema(definition, options);
    }
1106917
function generateResourceListing (options) {
  var plurals = options.controllers.map(function (controller) {
    return controller.model().plural();
  });
  var listing = {
    apiVersion: options.version,
    swaggerVersion: '1.1',
    basePath: options.basePath,
    apis: plurals.map(function (plural) {
      return { path: '/documentation/' + plural, description: 'Operations about ' + plural + '.' };
    })
  };

  return listing;
}
304510
def extract_definitions(alist, level=None, endpoint=None, verb=None,
                        prefix_ids=False):
    
    endpoint = endpoint or request.endpoint.lower()
    verb = verb or request.method.lower()
    endpoint = endpoint.replace('.', '_')

    def _extract_array_defs(source):
        """
        Extracts definitions identified by `id`
        """
        # extract any definitions that are within arrays
        # this occurs recursively
        ret = []
        items = source.get('items')
        if items is not None and 'schema' in items:
            ret += extract_definitions(
                [items], level + 1, endpoint, verb, prefix_ids)
        return ret

    # for tracking level of recursion
    if level is None:
        level = 0

    defs = list()
    for item in alist:
        if not getattr(item, 'get'):
            raise RuntimeError('definitions must be a list of dicts')
        schema = item.get("schema")
        if schema is not None:
            schema_id = schema.get("id")
            if schema_id is not None:
                # add endpoint_verb to schema id to avoid conflicts
                if prefix_ids:
                    schema['id'] = schema_id = "{}_{}_{}".format(
                        endpoint, verb, schema_id
                    )
                # ^ api['SWAGGER']['prefix_ids'] = True
                # ... for backwards compatibility with <= 0.5.14

                defs.append(schema)
                ref = {"$ref": "#/definitions/{}".format(schema_id)}
                # only add the reference as a schema if we are in a
                # response or a parameter i.e. at the top level
                # directly ref if a definition is used within another
                # definition
                if level == 0:
                    item['schema'] = ref
                else:
                    item.update(ref)
                    del item['schema']

            # extract any definitions that are within properties
            # this occurs recursively
            properties = schema.get('properties')
            if properties is not None:
                defs += extract_definitions(
                    properties.values(), level + 1, endpoint, verb, prefix_ids)

            defs += _extract_array_defs(schema)

        defs += _extract_array_defs(item)

    return defs
840132
def create_swagger_json_handler(app, **kwargs):
    

    spec = get_swagger_spec(app)
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    async def swagger(request):
        return HTTPResponse(
            body_bytes=encoded_spec,
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger
202886
def compile_swagger_schema(schema_dir, resource_listing):
    
    mapping = build_schema_mapping(schema_dir, resource_listing)
    resource_validators = ingest_resources(mapping, schema_dir)
    endpoints = list(build_swagger_12_endpoints(resource_listing, mapping))
    return SwaggerSchema(endpoints, resource_validators)
1003030
def swagger(self):
        

        # Make sure any changes to the paths are reflected back in output
        self._doc["paths"] = self.paths

        if self.security_definitions:
            self._doc["securityDefinitions"] = self.security_definitions
        if self.gateway_responses:
            self._doc[self._X_APIGW_GATEWAY_RESPONSES] = self.gateway_responses

        return copy.deepcopy(self._doc)
900339
def build_definitions_example(self):
        """"""
        for def_name, def_spec in self.specification.get('definitions', {}).items():
            self.build_one_definition_example(def_name)
477101
def build_schema(self):
        
        container = SchemaCollection(self)
        for t in [t for t in self.types if t.local()]:
            for root in t.contents():
                schema = Schema(root, self.url, self.options, container)
                container.add(schema)
        if not len(container):  # empty
            root = Element.buildPath(self.root, 'types/schema')
            schema = Schema(root, self.url, self.options, container)
            container.add(schema)
        self.schema = container.load(self.options)
        for s in [t.schema() for t in self.types if t.imported()]:
            self.schema.merge(s)
        return self.schema
983409
def dispatch_request(self, *args, **kwargs):
        
        if self.validation:
            specs = {}
            attrs = flasgger.constants.OPTIONAL_FIELDS + [
                'parameters', 'definitions', 'responses',
                'summary', 'description'
            ]
            for attr in attrs:
                specs[attr] = getattr(self, attr)
            definitions = {}
            specs.update(convert_schemas(specs, definitions))
            specs['definitions'] = definitions
            flasgger.utils.validate(
                specs=specs, validation_function=self.validation_function)
        return super(SwaggerView, self).dispatch_request(*args, **kwargs)
1281566
def definition(self, name, tags=None):
        
        def wrapper(obj):
            self.definition_models.append(SwaggerDefinition(name, obj,
                                                            tags=tags))
            return obj
        return wrapper
326359
def generate_and_merge_schemas(samples):
    
    merged = generate_schema_for_sample(next(iter(samples)))

    for sample in samples:
        merged = merge_schema(merged, generate_schema_for_sample(sample))

    return merged
987552
def swagger_schema(self, request):
        """"""
        if self.parent is None:
            return {}

        spec = APISpec(
            self.parent.name, self.parent.cfg.get('VERSION', ''),
            plugins=['apispec.ext.marshmallow'], basePatch=self.prefix
        )

        for paths, handler in self.handlers.items():
            spec.add_tag({
                'name': handler.name,
                'description': utils.dedent(handler.__doc__ or ''),
            })
            for path in paths:
                operations = {}
                for http_method in handler.methods:
                    method = getattr(handler, http_method.lower())
                    operation = OrderedDict({
                        'tags': [handler.name],
                        'summary': method.__doc__,
                        'produces': ['application/json'],
                        'responses': {200: {'schema': {'$ref': {'#/definitions/' + handler.name}}}}
                    })
                    operation.update(utils.load_yaml_from_docstring(method.__doc__) or {})
                    operations[http_method.lower()] = operation

                spec.add_path(self.prefix + path, operations=operations)

            if getattr(handler, 'Schema', None):
                kwargs = {}
                if getattr(handler.meta, 'model', None):
                    kwargs['description'] = utils.dedent(handler.meta.model.__doc__ or '')
                spec.definition(handler.name, schema=handler.Schema, **kwargs)

        return deepcopy(spec.to_dict())