Exemplo n.º 1
0
def validator(request, schema=None, deserializer=None, **kwargs):
    import marshmallow
    from cornice.validators import extract_cstruct

    if deserializer is None:
        deserializer = extract_cstruct

    if schema is None:
        return

    schema = _instantiate_schema(schema)
    schema.context.setdefault('request', request)

    cstruct = deserializer(request)
    try:
        deserialized = schema.load(cstruct)
        if isinstance(deserialized, tuple):
            deserialized, errors = deserialized[0], deserialized[1]
            if errors:
                raise marshmallow.ValidationError(errors)
    except marshmallow.ValidationError as err:
        normalized_errors = _message_normalizer(err)
        for location, details in normalized_errors.items():
            location = location if location != '_schema' else ''
            if hasattr(details, 'items'):
                for subfield, msg in details.items():
                    request.errors.add(location, subfield, msg)
            else:
                request.errors.add(location, location, details)
    else:
        request.validated.update(deserialized)
Exemplo n.º 2
0
 def _deserialize(self, value, attr, data, **kwargs):
     schema.context.setdefault('request', request)
     deserialized = schema.load(value)
     if isinstance(deserialized, tuple):
         deserialized, errors = deserialized[0], deserialized[1]
         if errors:
             raise marshmallow.ValidationError(
                 errors)  # pragma: no cover
     return deserialized
Exemplo n.º 3
0
 def _deserialize(self, value, attr, data, **kwargs):
     schema.context.setdefault('request', request)
     deserialized = schema.load(value)
     # marshmallow 2.x returns a tuple, 3/x will always throw
     # and returns just data
     if isinstance(deserialized, tuple):
         deserialized, errors = deserialized[0], deserialized[1]
         # this should cover both non-strict and strict forms
         if errors:
             raise marshmallow.ValidationError(
                 errors)  # pragma: no cover
     return deserialized
Exemplo n.º 4
0
def validator(request, schema=None, deserializer=None, **kwargs):
    """
    Validate the full request against the schema defined on the service.

    Each attribute of the request is deserialized, validated and stored in the
    ``request.validated`` attribute
    (eg. body in ``request.validated['body']``).

    .. note::

        If no schema is defined, this validator does nothing.

    :param request: Current request
    :type request: :class:`~pyramid:pyramid.request.Request`

    :param schema: The marshmallow schema
    :param deserializer: Optional deserializer, defaults to
        :func:`cornice.validators.extract_cstruct`
    """
    import marshmallow
    from cornice.validators import extract_cstruct

    if deserializer is None:
        deserializer = extract_cstruct

    if schema is None:
        return

    schema = _instantiate_schema(schema)
    schema.context.setdefault('request', request)

    cstruct = deserializer(request)
    try:
        deserialized = schema.load(cstruct)
        # marshmallow 2.x returns a tuple, 3/x will always throw
        # and returns just data
        if isinstance(deserialized, tuple):
            deserialized, errors = deserialized[0], deserialized[1]
            # this should cover both non-strict and strict forms
            if errors:
                raise marshmallow.ValidationError(errors)
    except marshmallow.ValidationError as err:
        # translate = request.localizer.translate
        normalized_errors = _message_normalizer(err)
        for location, details in normalized_errors.items():
            location = location if location != '_schema' else ''
            if hasattr(details, 'items'):
                for subfield, msg in details.items():
                    request.errors.add(location, subfield, msg)
            else:
                request.errors.add(location, location, details)
    else:
        request.validated.update(deserialized)
def parse(schema: schema, request: request) -> (dict, dict):
    result = {}
    try:
        result = schema.load(data=request.media)
    except Exception as e:
        if not result:
            if hasattr(e, 'messages'):
                result = e.messages
        raise RequestParsingError(
            description='Unable to parse request body into schema object.',
            errors=result)

    return result
Exemplo n.º 6
0
 def _deserialize(self, value, attr, data, **kwargs):
     schema.context.setdefault('request', request)
     deserialized = schema.load(value)
     return deserialized
Exemplo n.º 7
0
from marshmallow import schema, fields, post_load, post_dump, validate


class User:
    def __init__(self, name, password="******"):
        self.name = name
        self.password = password


class UserSchema(schema.Schema):
    name = fields.Str(required=True, validate=[validate.Length(max=6)])
    password = fields.Str(required=True)

    # TODO: 小 BUG, 一定要加上 **kw
    @post_load
    def to_orm(self, data, **kwargs):
        return User(**data)


schema = UserSchema()
# 反序列化 load
# request.json
user_data = {"name": "yuz234f3rf"}

data = schema.load(user_data)
# 得到的还是一个字典。, 而不是通常意义上的 python 对象 User
# 数据校验
print(data)
# print(data.name)
# print(data.password)
Exemplo n.º 8
0
 def exec(self, *args):
     in_args = None
     if self.in_schema:
         schema = self.in_schema(many=False, unknown=EXCLUDE)
         in_args = schema.load(args)
Exemplo n.º 9
0
def load_config(cls: Type["BaseMarshmallowConfig"], **kwargs):  # noqa 0821
    """Takes a marshmallow class and instantiates it with the given keyword args as parameters."""
    assert_is_a_marshmallow_class(cls)
    schema = cls.Schema()
    return schema.load(kwargs)
Exemplo n.º 10
0
    # # TODO: 小 BUG, 一定要加上 **kw
    @post_load
    def to_orm(self, data):
        return User(**data)
        # user = User(**data)
        # user.save()
        # return user


schema = UserSchema()
# 反序列化 load
# request.json
user_data = {"name": "yuz234", "password": "******"}

data = schema.load(user_data)
# 得到的还是一个字典。, 而不是通常意义上的 python 对象 User
# 数据校验
print(data)
print(data.name)
print(data.password)

# ------ 内置校验器Validator ------
from marshmallow import schema, fields, validate, ValidationError, validates


class UserSchema(schema.Schema):
    username = fields.Str(yalidate=[validate.Length(max=64)])
    password = fields.Str(validate=[validate.Regexp(r"/^(?=.*[a-ZA-Z])[\s\S]{8,32}$/")])
    age = fields.Int(validate=[validate.Range(min=6, max=200)])
    gender = fields.Str(va1idate=[validate.OneOf(['男', '女', '未知'])])