Exemplo n.º 1
0
def openapi_format(format="yaml",
                   server="localhost",
                   no_servers=False,
                   return_tags=False):
    extra_specs = {
        'info': {
            'description':
            'The Faraday REST API enables you to interact with '
            '[our server](https://github.com/infobyte/faraday).\n'
            'Use this API to interact or integrate with Faraday'
            ' server. This page documents the REST API, with HTTP'
            ' response codes and example requests and responses.'
        },
        'security': {
            "ApiKeyAuth": []
        }
    }

    if not no_servers:
        extra_specs['servers'] = [{'url': f'https://{server}/_api'}]

    spec = APISpec(
        title="Faraday API",
        version="2",
        openapi_version="3.0.2",
        plugins=[FaradayAPIPlugin(),
                 FlaskPlugin(),
                 MarshmallowPlugin()],
        **extra_specs)
    api_key_scheme = {
        "type": "apiKey",
        "in": "header",
        "name": "Authorization"
    }

    spec.components.security_scheme("API_KEY", api_key_scheme)
    response_401_unauthorized = {
        "description":
        "You are not authenticated or your API key is missing "
        "or invalid"
    }
    spec.components.response("UnauthorizedError", response_401_unauthorized)

    tags = set()

    with get_app().test_request_context():
        for endpoint in get_app().view_functions.values():
            spec.path(view=endpoint, app=get_app())

        # Set up global tags
        spec_yaml = yaml.load(spec.to_yaml(), Loader=yaml.SafeLoader)
        for path_value in spec_yaml["paths"].values():
            for data_value in path_value.values():
                if 'tags' in data_value and any(data_value['tags']):
                    for tag in data_value['tags']:
                        tags.add(tag)
        for tag in sorted(tags):
            spec.tag({'name': tag})

        if return_tags:
            return sorted(tags)

        if format.lower() == "yaml":
            print(spec.to_yaml())
        else:
            print(json.dumps(spec.to_dict(), indent=2))
Exemplo n.º 2
0
cors = CORS(allow_all_origins=True)

app=falcon.API(middleware=[PeeweeConnectionMW(),cors.middleware])
    #consider also falcon_cors.CORS with allow_credentials_all_origins etc
spec = APISpec(
    title='API Anonimizada',
    version='0.9.1',
    openapi_version='3.0.0',  #2.0 usa consumes, 3.0 usa requestBody pero no sake muy bien en falcon_swagger_ui
    info=dict(description="Modelo de API para datos anonimizados espacial y temporalmente"),
    plugins=[
        FalconPlugin(app),
    ],
)
spec.components.security_scheme("claveSimple",{"type": "http", "scheme": "basic"})
spec.tag({"name":"admin","description":"necesitan privilegios"})
spec.tag({"name":"csv","description":"fichero en CSV"})
spec.tag({"name":"open","description":"no necesita auth"}) 

### batch tasks, should be suitable for parallelism

def makeBatch(data,t,salt):
    datalot=[]
    conflictset=set()
    idsKeyDict=t.idsKeys
    for linetime,lineid,line in data:
        #print(line,idsKeyDict)
        for k in idsKeyDict:
                    if k in line:
                        if idsKeyDict[k]=="":
                            del line[k]
Exemplo n.º 3
0
class ApiSpecPlugin(BasePlugin, DocBlueprintMixin):
    """Плагин для связки json_api и swagger"""

    def __init__(self, app=None, spec_kwargs=None, decorators=None, tags: Dict[str, str] = None):
        """

        :param spec_kwargs:
        :param decorators:
        :param tags: {'<name tag>': '<description tag>'}
        """
        self.decorators_for_autodoc = decorators or tuple()
        self.spec_kwargs = spec_kwargs if spec_kwargs is not None else {}
        self.spec = None
        self.spec_tag = {}
        self.spec_schemas = {}
        self.app = None
        self._fields = []
        # Use lists to enforce order
        self._fields = []
        self._converters = []

        # Инициализация ApiSpec
        self.app = app
        self._app = app
        # Initialize spec
        openapi_version = app.config.get("OPENAPI_VERSION", "2.0")
        openapi_major_version = int(openapi_version.split(".")[0])
        if openapi_major_version < 3:
            base_path = app.config.get("APPLICATION_ROOT")
            # Don't pass basePath if '/' to avoid a bug in apispec
            # https://github.com/marshmallow-code/apispec/issues/78#issuecomment-431854606
            # TODO: Remove this condition when the bug is fixed
            if base_path != "/":
                self.spec_kwargs.setdefault("basePath", base_path)
        self.spec_kwargs.update(app.config.get("API_SPEC_OPTIONS", {}))
        self.spec = APISpec(
            app.name,
            app.config.get("API_VERSION", "1"),
            openapi_version=openapi_version,
            plugins=[MarshmallowPlugin(), RestfulPlugin()],
            **self.spec_kwargs,
        )

        tags = tags if tags else {}
        for tag_name, tag_description in tags.items():
            self.spec_tag[tag_name] = {"name": tag_name, "description": tag_description, "add_in_spec": False}
            self._add_tags_in_spec(self.spec_tag[tag_name])

    def after_init_plugin(self, *args, app=None, **kwargs):
        # Register custom fields in spec
        for args in self._fields:
            self.spec.register_field(*args)
        # Register custom converters in spec
        for args in self._converters:
            self.spec.register_converter(*args)

        # Initialize blueprint serving spec
        self._register_doc_blueprint()

    def after_route(
        self,
        resource: Union[ResourceList, ResourceDetail] = None,
        view=None,
        urls: Tuple[str] = None,
        self_json_api: Api = None,
        tag: str = None,
        default_parameters=None,
        default_schema: Schema = None,
        **kwargs,
    ) -> None:
        """

        :param resource:
        :param view:
        :param urls:
        :param self_json_api:
        :param str tag: тег под которым стоит связать этот ресурс
        :param default_parameters: дефолтные поля для ресурса в сваггер (иначе просто инициализируется [])
        :param Schema default_schema: схема, которая подставиться вместо схемы в стили json api
        :param kwargs:
        :return:
        """
        # Register views in API documentation for this resource
        # resource.register_views_in_doc(self._app, self.spec)
        # Add tag relative to this resource to the global tag list

        # We add definitions (models) to the apiscpec
        if resource.schema:
            self._add_definitions_in_spec(resource.schema)

        # We add tags to the apiscpec
        tag_name = view.title()
        if tag is None and view.title() not in self.spec_tag:
            dict_tag = {"name": view.title(), "description": "", "add_in_spec": False}
            self.spec_tag[dict_tag["name"]] = dict_tag
            self._add_tags_in_spec(dict_tag)
        elif tag:
            tag_name = self.spec_tag[tag]["name"]

        urls = urls if urls else tuple()
        for i_url in urls:
            self._add_paths_in_spec(
                path=i_url,
                resource=resource,
                default_parameters=default_parameters,
                default_schema=default_schema,
                tag_name=tag_name,
                **kwargs,
            )

    @property
    def param_id(self) -> dict:
        return {
            "in": "path",
            "name": "id",
            "required": True,
            "type": "integer",
            "format": "int32",
        }

    @classmethod
    def _get_operations_for_all(cls, tag_name: str, default_parameters: list) -> Dict[str, Any]:
        """
        Creating base dict

        :param tag_name:
        :param default_parameters:
        :return:
        """
        return {
            "tags": [tag_name],
            "produces": ["application/json"],
            "parameters": default_parameters if default_parameters else [],
        }

    @classmethod
    def __get_parameters_for_include_models(cls, resource: Resource) -> dict:
        fields_names = [
            i_field_name
            for i_field_name, i_field in resource.schema._declared_fields.items()
            if isinstance(i_field, Relationship)
        ]
        models_for_include = ",".join(fields_names)
        example_models_for_include = "\n".join([f"`{f}`" for f in fields_names])
        return {
            "default": models_for_include,
            "name": "include",
            "in": "query",
            "format": "string",
            "required": False,
            "description": f"Related relationships to include.\nAvailable:\n{example_models_for_include}",
        }

    @classmethod
    def __get_parameters_for_sparse_fieldsets(cls, resource: Resource, description: str) -> dict:
        # Sparse Fieldsets
        return {
            "name": f"fields[{resource.schema.Meta.type_}]",
            "in": "query",
            "type": "array",
            "required": False,
            "description": description.format(resource.schema.Meta.type_),
            "items": {"type": "string", "enum": list(resource.schema._declared_fields.keys())},
        }

    def __get_parameters_for_declared_fields(self, resource, description) -> Generator[dict, None, None]:
        type_schemas = {resource.schema.Meta.type_}
        for i_field_name, i_field in resource.schema._declared_fields.items():
            if not (isinstance(i_field, Relationship) and i_field.schema.Meta.type_ not in type_schemas):
                continue
            schema_name = create_schema_name(schema=i_field.schema)
            new_parameter = {
                "name": f"fields[{i_field.schema.Meta.type_}]",
                "in": "query",
                "type": "array",
                "required": False,
                "description": description.format(i_field.schema.Meta.type_),
                "items": {
                    "type": "string",
                    "enum": list(self.spec.components._schemas[schema_name]["properties"].keys()),
                },
            }
            type_schemas.add(i_field.schema.Meta.type_)
            yield new_parameter

    @property
    def __list_filters_data(self) -> tuple:
        return (
            {
                "default": 1,
                "name": "page[number]",
                "in": "query",
                "format": "int64",
                "required": False,
                "description": "Page offset",
            },
            {
                "default": 10,
                "name": "page[size]",
                "in": "query",
                "format": "int64",
                "required": False,
                "description": "Max number of items",
            },
            {"name": "sort", "in": "query", "format": "string", "required": False, "description": "Sort",},
            {
                "name": "filter",
                "in": "query",
                "format": "string",
                "required": False,
                "description": "Filter (https://flask-combo-jsonapi.readthedocs.io/en/latest/filtering.html)",
            },
        )

    @classmethod
    def _update_parameter_for_field_spec(cls, new_param: dict, fld_sped: dict) -> None:
        """
        :param new_param:
        :param fld_sped:
        :return:
        """
        if "items" in fld_sped:
            new_items = {
                "type": fld_sped["items"].get("type"),
            }
            if "enum" in fld_sped["items"]:
                new_items["enum"] = fld_sped["items"]["enum"]
            new_param.update({"items": new_items})

    def __get_parameter_for_not_nested(self, field_name, field_spec) -> dict:
        new_parameter = {
            "name": f"filter[{field_name}]",
            "in": "query",
            "type": field_spec.get("type"),
            "required": False,
            "description": f"{field_name} attribute filter",
        }
        self._update_parameter_for_field_spec(new_parameter, field_spec)
        return new_parameter

    def __get_parameter_for_nested_with_filtering(self, field_name, field_jsonb_name, field_jsonb_spec):
        new_parameter = {
            "name": f"filter[{field_name}{SPLIT_REL}{field_jsonb_name}]",
            "in": "query",
            "type": field_jsonb_spec.get("type"),
            "required": False,
            "description": f"{field_name}{SPLIT_REL}{field_jsonb_name} attribute filter",
        }
        self._update_parameter_for_field_spec(new_parameter, field_jsonb_spec)
        return new_parameter

    def __get_parameters_for_nested_with_filtering(self, field, field_name) -> Generator[dict, None, None]:
        # Allow JSONB filtering
        field_schema_name = create_schema_name(schema=field.schema)
        component_schema = self.spec.components._schemas[field_schema_name]
        for i_field_jsonb_name, i_field_jsonb in field.schema._declared_fields.items():
            i_field_jsonb_spec = component_schema["properties"][i_field_jsonb_name]
            if i_field_jsonb_spec.get("type") == "object":
                # Пропускаем создание фильтров для dict. Просто не понятно как фильтровать по таким
                # полям
                continue
            new_parameter = self.__get_parameter_for_nested_with_filtering(
                field_name, i_field_jsonb_name, i_field_jsonb_spec,
            )
            yield new_parameter

    def __get_list_resource_fields_filters(self, resource) -> Generator[dict, None, None]:
        schema_name = create_schema_name(schema=resource.schema)
        for i_field_name, i_field in resource.schema._declared_fields.items():
            i_field_spec = self.spec.components._schemas[schema_name]["properties"][i_field_name]
            if not isinstance(i_field, fields.Nested):
                if i_field_spec.get("type") == "object":
                    # Skip filtering by dicts
                    continue
                yield self.__get_parameter_for_not_nested(i_field_name, i_field_spec)
            elif getattr(i_field.schema.Meta, "filtering", False):
                yield from self.__get_parameters_for_nested_with_filtering(i_field, i_field_name)

    def _get_operations_for_get(self, resource, tag_name, default_parameters):
        operations_get = self._get_operations_for_all(tag_name, default_parameters)
        operations_get["responses"] = {
            **status[HTTPStatus.OK],
            **status[HTTPStatus.NOT_FOUND],
        }

        if issubclass(resource, ResourceDetail):
            operations_get["parameters"].append(self.param_id)

        if resource.schema is None:
            return operations_get

        description = "List that refers to the name(s) of the fields to be returned `{}`"

        operations_get["parameters"].extend(
            (
                self.__get_parameters_for_include_models(resource),
                self.__get_parameters_for_sparse_fieldsets(resource, description),
            )
        )
        operations_get["parameters"].extend(self.__get_parameters_for_declared_fields(resource, description))

        if issubclass(resource, ResourceList):
            operations_get["parameters"].extend(self.__list_filters_data)
            operations_get["parameters"].extend(self.__get_list_resource_fields_filters(resource))

        return operations_get

    def _get_operations_for_post(self, schema: dict, tag_name: str, default_parameters: list) -> dict:
        operations = self._get_operations_for_all(tag_name, default_parameters)
        operations["responses"] = {
            "201": {"description": "Created"},
            "202": {"description": "Accepted"},
            "403": {"description": "This implementation does not accept client-generated IDs"},
            "404": {"description": "Not Found"},
            "409": {"description": "Conflict"},
        }
        operations["parameters"].append(
            {
                "name": "POST body",
                "in": "body",
                "schema": schema,
                "required": True,
                "description": f"{tag_name} attributes",
            }
        )
        return operations

    def _get_operations_for_patch(self, schema: dict, tag_name: str, default_parameters: list) -> dict:
        operations = self._get_operations_for_all(tag_name, default_parameters)
        operations["responses"] = {
            "200": {"description": "Success"},
            "201": {"description": "Created"},
            "204": {"description": "No Content"},
            "403": {"description": "Forbidden"},
            "404": {"description": "Not Found"},
            "409": {"description": "Conflict"},
        }
        operations["parameters"].append(self.param_id)
        operations["parameters"].append(
            {
                "name": "POST body",
                "in": "body",
                "schema": schema,
                "required": True,
                "description": f"{tag_name} attributes",
            }
        )
        return operations

    def _get_operations_for_delete(self, tag_name: str, default_parameters: list) -> dict:
        operations = self._get_operations_for_all(tag_name, default_parameters)
        operations["parameters"].append(self.param_id)
        operations["responses"] = {
            "200": {"description": "Success"},
            "202": {"description": "Accepted"},
            "204": {"description": "No Content"},
            "403": {"description": "Forbidden"},
            "404": {"description": "Not Found"},
        }
        return operations

    def _add_paths_in_spec(
        self,
        path: str = "",
        resource: Any = None,
        tag_name: str = "",
        default_parameters: List = None,
        default_schema: Schema = None,
        **kwargs,
    ) -> None:
        operations = {}
        methods: Set[str] = {i_method.lower() for i_method in resource.methods}

        attributes = {}
        if resource.schema:
            attributes = {"$ref": f"#/definitions/{create_schema_name(resource.schema)}"}
        schema = (
            default_schema
            if default_schema
            else {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "type": {
                                "type": "string",
                            },
                            "id": {
                                "type": "string",
                            },
                            "attributes": attributes,
                            "relationships": {
                                "type": "object",
                            },
                        },
                        "required": [
                            "type",
                        ],
                    },
                },
            }
        )

        if "get" in methods:
            operations["get"] = self._get_operations_for_get(resource, tag_name, default_parameters)
        if "post" in methods:
            operations["post"] = self._get_operations_for_post(schema, tag_name, default_parameters)
        if "patch" in methods:
            operations["patch"] = self._get_operations_for_patch(schema, tag_name, default_parameters)
        if "delete" in methods:
            operations["delete"] = self._get_operations_for_delete(tag_name, default_parameters)
        rule = None
        for i_rule in self.app.url_map._rules:
            if i_rule.rule == path:
                rule = i_rule
                break
        if APISPEC_VERSION_MAJOR < 1:
            self.spec.add_path(path=path, operations=operations, rule=rule, resource=resource, **kwargs)
        else:
            self.spec.path(path=path, operations=operations, rule=rule, resource=resource, **kwargs)

    def _add_definitions_in_spec(self, schema) -> None:
        """
        Add schema in spec
        :param schema: schema marshmallow
        :return:
        """
        name_schema = create_schema_name(schema)
        if name_schema not in self.spec_schemas and name_schema not in self.spec.components._schemas:
            self.spec_schemas[name_schema] = schema
            if APISPEC_VERSION_MAJOR < 1:
                self.spec.definition(name_schema, schema=schema)
            else:
                self.spec.components.schema(name_schema, schema=schema)

    def _add_tags_in_spec(self, tag: Dict[str, str]) -> None:
        """
        Add tags in spec
        :param tag: {'name': '<name tag>', 'description': '<tag description>', 'add_in_spec': <added tag in spec?>}
        :return:
        """
        if tag.get("add_in_spec", True) is False:
            self.spec_tag[tag["name"]]["add_in_spec"] = True
            tag_in_spec = {"name": tag["name"], "description": tag["description"]}
            if APISPEC_VERSION_MAJOR < 1:
                self.spec.add_tag(tag_in_spec)
            else:
                self.spec.tag(tag_in_spec)
Exemplo n.º 4
0
def generate_spec(request, swagger_info, plugins, filter_by_tags=False):
    """Generate OpenAPI Spec.

    This function will start the route introspection in Pyramid,
    looking for views with the following cornice_apispec and cornice predicates:

    * `schema`: Cornice predicate for Schema validator
    * `content_type`: Cornice/Pyramid predicate for Content-Type
    * `apispec_response_schemas`: (List) Response Schemas to add in Swagger
    * `apispec_tags`: (List) Tag List for view
    * `apispec_summary`: (Str) Short Summary for view operation in swagger
    * `apispec_description`: (Str) Long description for view operation in swagger
    * `apispec_show`: (Bool) Only views with this predicate will be included in Swagger

    Examples
    ^^^^^^^^

    ## Pyramid::

        @view_config(
            apispec_tags=['health'],
            apispec_summary="Returns healthcheck',
            apispec_description="Long description for operation",
            apispec_show=True)
        def health_check(request):
            request.response.status = 200
            request.response.body = "OK"
            return request.response

    ## Cornice Service::

        health_chech_service = Service(
            name='healthcheck_api',
            description='API HealthCheck',
            path="/health",
            apispec_show=True,
            apispec_tags=['health']
        )

        @health_chech_service.get(
            apispec_description="Long description for operation")
        def health_check(request):
            request.response.status = 200
            request.response.body = "OK"
            return request.response

    For more examples, please see ./examples folder.

    swagger_info options
    ^^^^^^^^^^^^^^^^^^^^
        * `title`: Api Title (default: 'OpenAPI Docs')
        * `main_description`: Main description for API. Accepts Markdown. (Default: '')
        * `version`: Api Version (default: '0.1.0')
        * `openapi_version`: OpenAPI version (default: '3.0.2')
        * `show_head`: Show HEAD requests in Swagger (default: False)
        * `show_options`: Show OPTIONS requests in Swagger (default: True)
        * `tag_list`: Tag dict list. No defaults.
            (example: [{'name': 'my tag', 'description': 'my description'}]).
        * `scheme`: http or https. If not informed, will extract from request.

        The `filter_by_tags` option will filter all views which does not have at
        least one tag from swagger_info tag_list.

    :param request: Pyramid Request
    :param swagger_info: Dict
    :param plugins: APISpec Plugins list
    :param filter_by_tags: Show only views with tags inside tag_list
    :return: Dict
    """
    def check_tag(view):
        if not filter_by_tags:
            return True
        view_tags = view['introspectable'].get('apispec_tags', [])
        openapi_tags = [tag['name'] for tag in spec._tags]
        if not view_tags:
            return False
        for tag in view_tags:
            if tag in openapi_tags:
                return True
        return False

    spec = APISpec(
        title=swagger_info.get('title', "OpenAPI Docs"),
        version=swagger_info.get('version', '0.1.0'),
        plugins=[plugin() for plugin in plugins],
        openapi_version=swagger_info.get('openapi_version', '3.0.2')
    )

    for tag in swagger_info.get('tag_list', []):
        spec.tag(tag)

    for view in request.registry.introspector.get_category('views'):
        show_apispec = view['introspectable'].get('apispec_show', False) is True
        has_request_methods = view['introspectable'].get('request_methods')
        has_tag = check_tag(view)
        if show_apispec and has_request_methods and has_tag:
            add_pyramid_paths(
                spec, view['introspectable'].get('route_name'),
                request=request,
                show_head=swagger_info.get('show_head', False),
                show_options=swagger_info.get('show_options', True)
            )

    openapi_spec = spec.to_dict()

    main_description = swagger_info.get('main_description', "")
    if main_description:
        openapi_spec['info'].update({'description': main_description})

    scheme = swagger_info.get('scheme', request.scheme)
    main_server_url = '{}://{}'.format(scheme, request.host)
    logger.info('Server URL for swagger json is {}'.format(main_server_url))
    openapi_spec.update({'servers': [{'url': main_server_url}]})

    return openapi_spec
Exemplo n.º 5
0
    msg = fields.String(description="A message.", required=True)


# register schemas with spec
spec.components.schema("Input", schema=InputSchema)
spec.components.schema("Output", schema=OutputSchema)

# add swagger tags that are used for endpoint annotation
tags = [
    {
        'name': 'testing',
        'description': 'For testing the API.'
    },
    {
        'name': 'Credentials',
        'description': 'Functions for credentials.'
    },
    {
        'name': 'auth',
        'description': 'Functions for Authentification in ika Web.'
    },
    {
        'name': 'google Gmail API',
        'description': 'Functions for using Gmail API.'
    },
]

for tag in tags:
    print(f"Adding tag: {tag['name']}")
    spec.tag(tag)