예제 #1
0
    def _get_operation_spec(handler):
        closure_vars = inspect.getclosurevars(handler)
        description = closure_vars.nonlocals.get('description', '')
        payload_schema = closure_vars.nonlocals.get('payload_schema')
        response_schema = closure_vars.nonlocals.get('response_schema')
        success_response_code = closure_vars.nonlocals.get(
            'success_response_code')

        openApiConverter = OpenAPIConverter(OPEN_API_VERSION, lambda s: None,
                                            None)

        request_body = {}
        response = {}

        if payload_schema:
            payload_schema_dict = openApiConverter.schema2jsonschema(
                payload_schema)

            request_body = dict(requestBody=dict(
                description=payload_schema.__name__,
                content={'application/json': {
                    'schema': payload_schema_dict
                }}))

        if response_schema:
            response_schema_dict = openApiConverter.schema2jsonschema(
                response_schema)

            response = {
                f'{success_response_code}': {
                    'description': 'success',
                    'content': {
                        'application/json': {
                            'schema': response_schema_dict
                        }
                    }
                }
            }
        else:
            response = {f'{success_response_code}': ''}

        return {
            'description': description,
            'responses': {
                **response
            },
            **request_body
        }
예제 #2
0
def openapi(request):
    return OpenAPIConverter(openapi_version=request.param)
예제 #3
0
import collections
import uuid

import marshmallow
from apispec.ext.marshmallow.openapi import OpenAPIConverter
from marshmallow import fields, ValidationError
from marshmallow.base import FieldABC

from channelstream.server_state import get_state

converter = OpenAPIConverter("2.0.0",
                             schema_name_resolver=lambda: None,
                             spec=None)

MSG_EDITABLE_KEYS = ("uuid", "timestamp", "user", "message", "edited")


def gen_uuid():
    return uuid.uuid4()


def validate_connection_id(conn_id):
    server_state = get_state()
    if conn_id not in server_state.connections:
        raise marshmallow.ValidationError("Unknown connection")


def validate_username(username):
    server_state = get_state()
    if username not in server_state.users:
        raise marshmallow.ValidationError("Unknown user")
예제 #4
0
 def _get_converter(self):
     return OpenAPIConverter("3.0", self._schema_name_resolver, None)
예제 #5
0
                        i.split('/')[-1], project=settings.TAX_ID, graph=settings.TAX_GRAPH, lang='de'
                    ),
                    'en': get_preflabel(
                        i.split('/')[-1], project=settings.TAX_ID, graph=settings.TAX_GRAPH, lang='en'
                    ),
                },
            }
        )

    if len(set(ACTIVE_TYPES)) < len(ACTIVE_TYPES):
        raise ImproperlyConfigured(_('Active schemas contain duplicate types'))


init()

converter = OpenAPIConverter(settings.OPEN_API_VERSION)


def schema2jsonschema(schema, force_text=False):
    jsonschema = converter.schema2jsonschema(schema)
    jsonschema['additionalProperties'] = False
    if force_text:
        # this is kinda hacky - change it if there's a better solution to force evaluation of lazy objects
        # inside a dict
        jsonschema = json.loads(json.dumps(jsonschema, cls=JSONEncoder))
    return jsonschema


def get_jsonschema(entry_type, force_text=False):
    for types, schema, _icon in ACTIVE_TUPLES:
        if entry_type in types:
예제 #6
0
try:
    from apispec.ext.marshmallow.openapi import OpenAPIConverter
    openapi = OpenAPIConverter(openapi_version='2.0')
    fields2jsonschema = openapi.fields2jsonschema
    field2property = openapi.field2property
except ImportError:
    from apispec.ext.marshmallow.swagger import fields2jsonschema, field2property
import flask_marshmallow
import marshmallow_mongoengine
from werkzeug import cached_property

from flask_restplus.model import Model as OriginalModel


class SchemaMixin(object):
    def __deepcopy__(self, memo):
        # XXX: Flask-RESTplus makes unnecessary data copying, while
        # marshmallow.Schema doesn't support deepcopyng.
        return self


class Schema(SchemaMixin, flask_marshmallow.Schema):
    def __init__(self, **kwargs):
        super(Schema, self).__init__(strict=True, **kwargs)


if flask_marshmallow.has_sqla:

    class ModelSchema(SchemaMixin, flask_marshmallow.sqla.ModelSchema):
        def __init__(self, **kwargs):
            if 'strict' not in kwargs:
예제 #7
0
import apispec
if tuple(int(i) for i in apispec.__version__.split('.')) <= (0, 38, 0):
    from apispec.ext.marshmallow.swagger import schema2parameters
else:
    from apispec.ext.marshmallow.openapi import OpenAPIConverter
    schema2parameters = OpenAPIConverter('2.0').schema2parameters

VALID_RESPONSE_FIELDS = {'schema', 'description', 'headers', 'examples'}


def docs(**kwargs):
    """
    Annotate the decorated view function with the specified Swagger
    attributes.

    Usage:

    .. code-block:: python

        from aiohttp import web

        @docs(tags=['my_tag'],
              summary='Test method summary',
              description='Test method description',
              parameters=[{
                      'in': 'header',
                      'name': 'X-Request-ID',
                      'schema': {'type': 'string', 'format': 'uuid'},
                      'required': 'true'
                  }]
              )
예제 #8
0
import collections
import uuid

import marshmallow
from apispec.ext.marshmallow.openapi import OpenAPIConverter
from marshmallow import fields, ValidationError
from marshmallow.base import FieldABC

from channelstream.server_state import get_state

converter = OpenAPIConverter("2.0.0")

MSG_EDITABLE_KEYS = ("uuid", "timestamp", "user", "message", "edited")

try:
    base_types = (unicode, basestring)
except NameError:
    base_types = (str, )


def gen_uuid():
    return uuid.uuid4()


def validate_connection_id(conn_id):
    server_state = get_state()
    if conn_id not in server_state.connections:
        raise marshmallow.ValidationError("Unknown connection")


def validate_username(username):
예제 #9
0
try:
    from apispec.ext.marshmallow.openapi import OpenAPIConverter
    openapi = OpenAPIConverter(openapi_version='2.0', schema_name_resolver=None, spec=None)
    schema2parameters = openapi.schema2parameters
except ImportError:
    from apispec.ext.marshmallow.swagger import schema2parameters

from flask_restx.swagger import Swagger as OriginalSwagger


class Swagger(OriginalSwagger):

    def parameters_for(self, doc):
        schema = doc['params']

        if not schema:
            return []
        if isinstance(schema, list):
            return schema
        if isinstance(schema, dict) and all(isinstance(field, dict) for field in schema.values()):
            return list(schema.values())

        if 'in' in schema.context and 'json' in schema.context['in']:
            default_location = 'body'
        else:
            default_location = 'query'

        return schema2parameters(schema, default_in=default_location, required=True)