Ejemplo n.º 1
0
 def respond_with_schema(self, schema: Schema, value, status: int = 200) -> Response:
     try:
         schema.validate(value)
     except ValidationError:
         return self.error("invalid schema supplied")
     result = schema.dump(value)
     return self.respond(result, status)
Ejemplo n.º 2
0
def validate_schema(schema: Schema, data: dict, remove_blank=False):
    """schema验证,验证成功返回数据,验证失败返回错误信息
    Parameters
    ----------
    schema:Schema: 验证规则
    data: 验证数据
    remove_blank : 是否去除空白字段

    Returns (data,errors)
    -------

    """
    if not data:
        return {}, []
    if not isinstance(data, dict):
        return Msg.PARAMS_ERROR, 400
    if remove_blank:
        for k, v in data.items():
            if v != "":
                data[k] = v
    try:
        validate_data = schema.validate(data)
        return validate_data, []
    except SchemaError as e:
        return {}, str(e.autos)
    else:
        return validate_data, []
Ejemplo n.º 3
0
def validate_file(name: str, schema: Schema):
    with console.status(f"Validating {name}...", spinner="dots"):
        errors = schema.validate(get_data_json(f"mtgjson/{name}.json"))

    if errors:
        pprint(errors["data"], max_length=10, console=console)
        console.print(f"❌ [bold red]{name} had {len(errors['data'])} errors")
    else:
        console.print(f"✅ [bold green]{name} validated")
Ejemplo n.º 4
0
    def validate(schema: Schema, data):
        error_msgs = schema.validate(data)
        if not error_msgs:
            return

        if '_schema' in error_msgs and error_msgs['_schema']:
            msg = ', '.join(error_msgs['_schema'])
            raise CommonException(error_code=error_codes.SERVER_PARAM_INVALID,
                                  msg=msg)

        raise CommonException(error_code=error_codes.SERVER_PARAM_INVALID,
                              data=error_msgs)
Ejemplo n.º 5
0
def data_dump_and_validation(schema: Schema, data: Any) -> Dict:
    """
    Use a marshmallow schema to dump and validate input data

    :param schema: the schema to use to dump an object and validate it
    :param data: the data to dump and validate
    :return: the resulting dumped data from marshmallow
    """
    val = schema.dump(data)
    errors = schema.validate(val)

    if errors:
        raise ValidationError(errors)

    return val
Ejemplo n.º 6
0
    def build_response(self, schema: Schema, response):
        """
        Validate the given response against a given Schema.
        Return the response data as a serialized object according to the given Schema's fields.

        :param schema:
        :param response:
        :return:
        """
        # Validate that schema.
        # This is not normally done with responses, but I want to be strict about ensuring the schema is up-to-date
        validation_errors = schema.validate(response)

        if validation_errors:
            # Throw an exception here with all the errors.
            # This will be caught and handled by the 500 internal error
            raise exceptions.ValidationError(validation_errors)

        # Build schema object from response
        data = schema.dump(response)
        return data
Ejemplo n.º 7
0
    def read_json_request(self, schema: Schema):
        """

        :param schema:
        :type schema: Schema descendant
        :return:
        """
        # Ensure body can be JSON decoded
        try:
            json_data = json.loads(self.request.body)
        except JSONDecodeError as e:
            self.set_status(self.STATUS_ERROR_EXTERNAL, reason=str(e))
            self.write_error()
            raise BaseApiError("Expected request body to be JSON. Received '{}'".format(self.request.body))

        request_validation_errors = schema.validate(json_data)
        if request_validation_errors:
            self.error_messages = request_validation_errors
            self.set_status(self.STATUS_ERROR_EXTERNAL, reason="Failed request schema validation")
            self.write_error()
            raise BaseApiError("Failed schema validation: {}".format(str(request_validation_errors)))

        return schema.dump(schema.load(json_data))
Ejemplo n.º 8
0
def validate_data(serializer: Schema, data: Dict):
    validation_errors = serializer.validate(data)
    if validation_errors:
        raise HTTPError(403, validation_errors)
    return True