Exemplo n.º 1
0
    def resolve(self, parameter: inspect.Parameter,
                path_params: ValidatedPathParams,
                query_params: ValidatedQueryParams):
        params = path_params if (parameter.name
                                 in path_params) else query_params
        has_default = parameter.default is not parameter.empty
        allow_null = parameter.default is None

        param_validator = {
            parameter.empty: validators.Any(),
            str: validators.String(allow_null=allow_null),
            int: validators.Integer(allow_null=allow_null),
            float: validators.Number(allow_null=allow_null),
            bool: validators.Boolean(allow_null=allow_null)
        }[parameter.annotation]

        validator = validators.Object(
            properties=[(parameter.name, param_validator)],
            required=[] if has_default else [parameter.name])

        try:
            params = validator.validate(params, allow_coerce=True)
        except validators.ValidationError as exc:
            raise exceptions.NotFound(exc.detail)
        return params.get(parameter.name, parameter.default)
Exemplo n.º 2
0
    def resolve(self, route: Route,
                query_params: http.QueryParams) -> ValidatedQueryParams:
        query_fields = route.link.get_query_fields()

        validator = validators.Object(
            properties=[(field.name,
                         field.schema if field.schema else validators.Any())
                        for field in query_fields],
            required=[field.name for field in query_fields if field.required])

        try:
            query_params = validator.validate(query_params, allow_coerce=True)
        except validators.ValidationError as exc:
            raise exceptions.BadRequest(exc.detail)
        return ValidatedQueryParams(query_params)
Exemplo n.º 3
0
    def resolve(self, route: Route,
                path_params: http.PathParams) -> ValidatedPathParams:
        path_fields = route.link.get_path_fields()

        validator = validators.Object(
            properties=[(field.name,
                         field.schema if field.schema else validators.Any())
                        for field in path_fields],
            required=[field.name for field in path_fields])

        try:
            path_params = validator.validate(path_params, allow_coerce=True)
        except validators.ValidationError as exc:
            raise exceptions.NotFound(exc.detail)
        return ValidatedPathParams(path_params)
Exemplo n.º 4
0
    def request(self, name: str, **params):
        link = self.lookup_link(name)

        validator = validators.Object(
            properties={field.name: validators.Any()
                        for field in link.fields},
            required=[field.name for field in link.fields if field.required],
            additional_properties=False)
        validator.validate(params)

        method = link.method
        url = self.get_url(link, params)
        query_params = self.get_query_params(link, params)
        (content, encoding) = self.get_content_and_encoding(link, params)

        return self.transport.send(method,
                                   url,
                                   query_params=query_params,
                                   content=content,
                                   encoding=encoding)
Exemplo n.º 5
0
    def __new__(cls, name, bases, attrs):
        properties = []
        for key, value in list(attrs.items()):
            if key in ['keys', 'items', 'values', 'get', 'validator']:
                msg = ('Cannot use reserved name "%s" on Type "%s", as it '
                       'clashes with the class interface.')
                raise ConfigurationError(msg % (key, name))

            elif isinstance(value, validators.Validator):
                attrs.pop(key)
                properties.append((key, value))

        properties = sorted(properties,
                            key=lambda item: item[1]._creation_counter)
        required = [
            key for key, value in properties if not value.has_default()
        ]

        attrs['validator'] = validators.Object(def_name=name,
                                               properties=properties,
                                               required=required,
                                               additional_properties=None)
        return super(TypeMetaclass, cls).__new__(cls, name, bases, attrs)
Exemplo n.º 6
0
def load_type(typename, struct, allow_null):
    attrs = {'allow_null': True} if allow_null else {}

    if typename == 'string':
        if 'minLength' in struct:
            attrs['min_length'] = struct['minLength']
        if 'maxLength' in struct:
            attrs['max_length'] = struct['maxLength']
        if 'pattern' in struct:
            attrs['pattern'] = struct['pattern']
        if 'format' in struct:
            attrs['format'] = struct['format']
        return validators.String(**attrs)

    if typename in ['number', 'integer']:
        if 'minimum' in struct:
            attrs['minimum'] = struct['minimum']
        if 'maximum' in struct:
            attrs['maximum'] = struct['maximum']
        if 'exclusiveMinimum' in struct:
            attrs['exclusive_minimum'] = struct['exclusiveMinimum']
        if 'exclusiveMaximum' in struct:
            attrs['exclusive_maximum'] = struct['exclusiveMaximum']
        if 'multipleOf' in struct:
            attrs['multiple_of'] = struct['multipleOf']
        if 'format' in struct:
            attrs['format'] = struct['format']
        if typename == 'integer':
            return validators.Integer(**attrs)
        return validators.Number(**attrs)

    if typename == 'boolean':
        return validators.Boolean(**attrs)

    if typename == 'object':
        if 'properties' in struct:
            attrs['properties'] = dict_type([
                (key, decode(value))
                for key, value in struct['properties'].items()
            ])
        if 'required' in struct:
            attrs['required'] = struct['required']
        if 'minProperties' in struct:
            attrs['min_properties'] = struct['minProperties']
        if 'maxProperties' in struct:
            attrs['max_properties'] = struct['maxProperties']
        if 'required' in struct:
            attrs['required'] = struct['required']
        if 'patternProperties' in struct:
            attrs['pattern_properties'] = dict_type([
                (key, decode(value))
                for key, value in struct['patternProperties'].items()
            ])
        if 'additionalProperties' in struct:
            if isinstance(struct['additionalProperties'], bool):
                attrs['additional_properties'] = struct['additionalProperties']
            else:
                attrs['additional_properties'] = decode(
                    struct['additionalProperties'])
        return validators.Object(**attrs)

    if typename == 'array':
        if 'items' in struct:
            if isinstance(struct['items'], list):
                attrs['items'] = [decode(item) for item in struct['items']]
            else:
                attrs['items'] = decode(struct['items'])
        if 'additionalItems' in struct:
            if isinstance(struct['additionalItems'], bool):
                attrs['additional_items'] = struct['additionalItems']
            else:
                attrs['additional_items'] = decode(struct['additionalItems'])
        if 'minItems' in struct:
            attrs['min_items'] = struct['minItems']
        if 'maxItems' in struct:
            attrs['max_items'] = struct['maxItems']
        if 'uniqueItems' in struct:
            attrs['unique_items'] = struct['uniqueItems']
        return validators.Array(**attrs)

    assert False
Exemplo n.º 7
0
JSON_SCHEMA = validators.Object(
    def_name='JSONSchema',
    properties=[
        ('$ref', validators.String()),
        ('type',
         validators.String() | validators.Array(items=validators.String())),
        ('enum', validators.Array(unique_items=True, min_items=1)),
        ('definitions',
         validators.Object(
             additional_properties=validators.Ref('JSONSchema'))),

        # String
        ('minLength', validators.Integer(minimum=0)),
        ('maxLength', validators.Integer(minimum=0)),
        ('pattern', validators.String(format='regex')),
        ('format', validators.String()),

        # Numeric
        ('minimum', validators.Number()),
        ('maximum', validators.Number()),
        ('exclusiveMinimum', validators.Boolean()),
        ('exclusiveMaximum', validators.Boolean()),
        ('multipleOf', validators.Number(minimum=0.0, exclusive_minimum=True)),

        # Object
        ('properties',
         validators.Object(additional_properties=validators.Ref('JSONSchema'))
         ),
        ('minProperties', validators.Integer(minimum=0)),
        ('maxProperties', validators.Integer(minimum=0)),
        ('patternProperties',
         validators.Object(
             additional_properties=validators.Ref('JSONSchema'))),
        ('additionalProperties',
         validators.Ref('JSONSchema') | validators.Boolean()),
        ('required',
         validators.Array(items=validators.String(),
                          min_items=1,
                          unique_items=True)),

        # Array
        ('items', validators.Ref('JSONSchema')
         | validators.Array(items=validators.Ref('JSONSchema'), min_items=1)),
        ('additionalItems',
         validators.Ref('JSONSchema') | validators.Boolean()),
        ('minItems', validators.Integer(minimum=0)),
        ('maxItems', validators.Integer(minimum=0)),
        ('uniqueItems', validators.Boolean()),
    ])
Exemplo n.º 8
0
import json
import re
from urllib.parse import urljoin, urlparse

from celerystar_apistar import validators
from celerystar_apistar.codecs import BaseCodec, JSONSchemaCodec
from celerystar_apistar.codecs.jsonschema import JSON_SCHEMA
from celerystar_apistar.compat import dict_type
from celerystar_apistar.document import Document, Field, Link, Section
from celerystar_apistar.exceptions import ParseError

SCHEMA_REF = validators.Object(
    properties={'$ref': validators.String(pattern='^#/components/schemas/')}
)


OPEN_API = validators.Object(
    def_name='OpenAPI',
    title='OpenAPI',
    properties=[
        ('openapi', validators.String()),
        ('info', validators.Ref('Info')),
        ('servers', validators.Array(items=validators.Ref('Server'))),
        ('paths', validators.Ref('Paths')),
        ('components', validators.Ref('Components')),
        ('security', validators.Ref('SecurityRequirement')),
        ('tags', validators.Array(items=validators.Ref('Tag'))),
        ('externalDocs', validators.Ref('ExternalDocumentation'))
    ],
    required=['openapi', 'info'],
    definitions={