Python pydantic.ValidationError() Examples

The following are 30 code examples of pydantic.ValidationError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pydantic , or try the search function .
Example #1
Source File: deps.py    From full-stack-fastapi-postgresql with MIT License 8 votes vote down vote up
def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = crud.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user 
Example #2
Source File: error.py    From Flask-Large-Application-Example with MIT License 7 votes vote down vote up
def broad_exception_handler(e: Exception):
    # TODO 에러를 세분화해서 잡는 것을 추천합니다.

    if isinstance(e, HTTPException):
        message = e.description
        code = e.code

    elif isinstance(e, ValidationError):
        message = json.loads(e.json())
        code = HTTPStatus.BAD_REQUEST

    else:
        message = ""
        code = HTTPStatus.INTERNAL_SERVER_ERROR

        if current_app.debug:
            import traceback

            traceback.print_exc()

    return jsonify({"error": message}), code 
Example #3
Source File: resource_model.py    From codo-admin with GNU General Public License v3.0 7 votes vote down vote up
def create_resource(data: dict):
    try:
        ResourceCreateModel(**data)
    except ValidationError as e:
        return dict(code=-1, msg=str(e))

    try:
        with DBContext('w', None, True) as db:
            db.add(ResourceOrm(**data))
    except IntegrityError as e:
        return dict(code=-2, msg='不要重复添加相同的资源组')

    return dict(code=0, msg="添加成功")


### 修改 
Example #4
Source File: domains.py    From LuWu with Apache License 2.0 6 votes vote down vote up
def purchase_domain(
    db: Session = Depends(get_db),
    *,
    domain_profile: PurchaseDomainSchema
):
    domain_isp = crud_isp.get(
        db_session=db,
        id=domain_profile.isp_id,
    )
    if domain_isp and domain_isp.provider_name != domain_profile.provider_name:
        raise ValidationError(
            [ErrorWrapper(Exception('provider_name is not matched'), loc="provider_name")],
            model=PurchaseDomainSchema,
        )

    purchase_task = celery_app.send_task(
        "purchase_domain", kwargs=domain_profile.dict()
    )
    purchase_result = purchase_task.get()
    return dict(result=purchase_result) 
Example #5
Source File: bragi_client.py    From idunn with Apache License 2.0 6 votes vote down vote up
def raw_autocomplete(self, params, body=None):
        url = settings["BRAGI_BASE_URL"] + "/autocomplete"
        if body:
            response = await self.client.post(url, params=params, json=body)
        else:
            response = await self.client.get(url, params=params)

        if response.status_code != httpx.codes.ok:
            try:
                explain = response.json()["long"]
            except (IndexError, JSONDecodeError):
                explain = response.text
            logger.error(
                'Request to Bragi returned with unexpected status %d: "%s"',
                response.status_code,
                explain,
            )
            raise HTTPException(503, "Unexpected geocoder error")

        try:
            return response.json()
        except (JSONDecodeError, pydantic.ValidationError) as e:
            logger.exception("Autocomplete invalid response")
            raise HTTPException(503, "Invalid response from the geocoder") 
Example #6
Source File: util.py    From pandaSDMX with Apache License 2.0 6 votes vote down vote up
def __setattr__(self, name, value):
        if (self.__config__.extra is not Extra.allow and name not in
                self.__fields__):
            raise ValueError(f'"{self.__class__.__name__}" object has no field'
                             f' "{name}"')
        elif not self.__config__.allow_mutation:
            raise TypeError(f'"{self.__class__.__name__}" is immutable and '
                            'does not support item assignment')
        elif (self.__config__.validate_assignment and name not in
              self.__config__.validate_assignment_exclude):
            if self.__config__.validate_assignment == 'limited':
                kw = {'include': {}}
            else:
                kw = {'exclude': {name}}
            known_field = self.__fields__.get(name, None)
            if known_field:
                value, error_ = known_field.validate(value, self.dict(**kw),
                                                     loc=name)
                if error_:
                    raise ValidationError([error_], type(self))
        self.__dict__[name] = value
        self.__fields_set__.add(name) 
Example #7
Source File: recycling.py    From idunn with Apache License 2.0 6 votes vote down vote up
def from_es(cls, place, lang):
        if not recycling_client.enabled:
            # Data source is not configured
            return None

        if place.PLACE_TYPE != "poi":
            return None

        if place.get_class_name() != "recycling":
            return None

        if not is_poi_in_finistere(place):
            return None

        try:
            containers = cls.fetch_containers(place)
        except (RequestException, ValidationError):
            logger.warning("Failed to fetch recycling containers data", exc_info=True)
            return None

        if not containers:
            return None
        return cls(containers=containers) 
Example #8
Source File: test_agents_resource.py    From asgard-api with MIT License 6 votes vote down vote up
def test_it_raises_a_validation_error_if_type_is_invalid(self):
        agents = [
            dict(
                type="XABLAU",
                id="id",
                hostname="hostname",
                active="active",
                version="version",
                port=8080,
                used_resources={"bla": "used_resources"},
                attributes={"data": "attributes"},
                resources={"data": "resources"},
            )
        ]
        with self.assertRaises(ValidationError):
            AgentsResource(agents=agents) 
Example #9
Source File: jobs.py    From asgard-api with MIT License 6 votes vote down vote up
def validate_input(handler):
    async def _wrapper(wrapper: RequestWrapper):
        try:
            req_body = await wrapper.http_request.json()
        except JSONDecodeError as e:
            return json_response(
                ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
                status=HTTPStatus.BAD_REQUEST,
            )

        try:
            job = ScheduledJob(**req_body)
        except ValidationError as e:
            return json_response(
                ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
                status=HTTPStatus.UNPROCESSABLE_ENTITY,
            )

        wrapper.types_registry.set(job)
        return await call_http_handler(wrapper.http_request, handler)

    return _wrapper 
Example #10
Source File: resource_model.py    From codo-admin with GNU General Public License v3.0 6 votes vote down vote up
def resource_user(data: dict):
    try:
        valid_data = ResourceUserModel(**data)
    except ValidationError as e:
        return dict(code=-1, msg=str(e))

    with DBContext('w', None, True) as db:
        try:
            db.query(UserResource).filter(UserResource.group_id == valid_data.id).delete(synchronize_session=False)
            for user_id in valid_data.user_list: db.add(UserResource(group_id=valid_data.id, user_id=user_id))
        except Exception as err:
            return dict(code=-2, msg='修改失败, {}'.format(str(err)))

    return dict(code=0, msg="修改成功")


### 根据用户昵称查询所有有权限资源 
Example #11
Source File: model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def validate_data(
        cls, data: Union[dict, list], context: str = None, on_error: callable = None,
    ):
        """Validate data which has already been loaded into a dictionary or list.

        context is a string that will be used to give context to error messages.
        on_error will be called for any validation errors with a dictionary in Pydantic error format

        https://pydantic-docs.helpmanual.io/usage/models/#error-handling
        """
        try:
            cls.parse_obj(data, context)
            return True
        except ValidationError as e:
            if on_error:
                for error in e.errors():
                    on_error(error)

            return False 
Example #12
Source File: test_entries.py    From optimade-python-tools with MIT License 6 votes vote down vote up
def test_simple_relationships():
    """Make sure relationship resources are added to the correct relationship"""

    good_relationships = (
        {"references": {"data": [{"id": "dijkstra1968", "type": "references"}]}},
        {"structures": {"data": [{"id": "dijkstra1968", "type": "structures"}]}},
    )
    for relationship in good_relationships:
        EntryRelationships(**relationship)

    bad_relationships = (
        {"references": {"data": [{"id": "dijkstra1968", "type": "structures"}]}},
        {"structures": {"data": [{"id": "dijkstra1968", "type": "references"}]}},
    )
    for relationship in bad_relationships:
        with pytest.raises(ValidationError):
            EntryRelationships(**relationship) 
Example #13
Source File: test_entries.py    From optimade-python-tools with MIT License 6 votes vote down vote up
def test_advanced_relationships():
    """Make sure the rules for the base resource 'meta' field are upheld"""

    relationship = {
        "references": {
            "data": [
                {
                    "id": "dijkstra1968",
                    "type": "references",
                    "meta": {
                        "description": "Reference for the search algorithm Dijkstra."
                    },
                }
            ]
        }
    }
    EntryRelationships(**relationship)

    relationship = {
        "references": {
            "data": [{"id": "dijkstra1968", "type": "references", "meta": {}}]
        }
    }
    with pytest.raises(ValidationError):
        EntryRelationships(**relationship) 
Example #14
Source File: test_links.py    From optimade-python-tools with MIT License 6 votes vote down vote up
def test_bad_links(starting_links):
    """Check badly formed links"""
    from pydantic import ValidationError

    bad_links = [
        {"aggregate": "wrong"},
        {"link_type": "wrong"},
        {"base_url": "example.org"},
        {"homepage": "www.example.org"},
        {"relationships": {}},
    ]

    for index, links in enumerate(bad_links):
        print(f"Now testing number {index}")
        bad_link = starting_links.copy()
        bad_link.update(links)
        with pytest.raises(ValidationError):
            LinksResource(**LinksMapper.map_back(bad_link))
        del bad_link 
Example #15
Source File: estimator.py    From gluon-ts with Apache License 2.0 6 votes vote down vote up
def from_hyperparameters(cls, **hyperparameters) -> "GluonEstimator":
        Model = getattr(cls.__init__, "Model", None)

        if not Model:
            raise AttributeError(
                f"Cannot find attribute Model attached to the "
                f"{fqname_for(cls)}. Most probably you have forgotten to mark "
                f"the class constructor as @validated()."
            )

        try:
            trainer = from_hyperparameters(Trainer, **hyperparameters)

            return cls(
                **Model(**{**hyperparameters, "trainer": trainer}).__dict__
            )
        except ValidationError as e:
            raise GluonTSHyperparametersError from e 
Example #16
Source File: _ensemble.py    From gluon-ts with Apache License 2.0 6 votes vote down vote up
def from_hyperparameters(
        cls, **hyperparameters
    ) -> "NBEATSEnsembleEstimator":
        Model = getattr(cls.__init__, "Model", None)

        if not Model:
            raise AttributeError(
                f"Cannot find attribute Model attached to the "
                f"{fqname_for(cls)}. Most probably you have forgotten to mark "
                f"the class constructor as @validated()."
            )

        try:
            trainer = from_hyperparameters(Trainer, **hyperparameters)
            return cls(
                **Model(**{**hyperparameters, "trainer": trainer}).__dict__
            )
        except ValidationError as e:
            raise GluonTSHyperparametersError from e 
Example #17
Source File: util.py    From QCEngine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def model_wrapper(input_data: Dict[str, Any], model: "BaseModel") -> "BaseModel":
    """
    Wrap input data in the given model, or return a controlled error
    """

    if isinstance(input_data, dict):
        try:
            input_data = model(**input_data)
        except ValidationError as exc:
            raise InputError(
                f"Error creating '{model.__name__}', data could not be correctly parsed:\n{str(exc)}"
            ) from None
    elif isinstance(input_data, model):
        input_data = input_data.copy()
    else:
        raise InputError("Input type of {} not understood.".format(type(model)))

    # Older QCElemental compat
    try:
        input_data.extras
    except AttributeError:
        input_data = input_data.copy(update={"extras": {}})

    return input_data 
Example #18
Source File: test_structures.py    From optimade-python-tools with MIT License 5 votes vote down vote up
def test_more_good_structures(good_structures):
    """Check well-formed structures with specific edge-cases"""
    for index, structure in enumerate(good_structures):
        try:
            StructureResource(**StructureMapper.map_back(structure))
        except ValidationError:
            print(
                f"Good test structure {index} failed to validate from 'test_more_structures.json'"
            )
            raise 
Example #19
Source File: test_references.py    From optimade-python-tools with MIT License 5 votes vote down vote up
def test_bad_references():
    """Check badly formed references"""
    from pydantic import ValidationError

    bad_refs = [
        {"id": "AAAA", "type": "references", "doi": "10.1234/1234"},  # bad id
        {"id": "newton1687", "type": "references"},  # missing all fields
        {"id": "newton1687", "type": "reference", "doi": "10.1234/1234"},  # wrong type
    ]

    for ref in bad_refs:
        with pytest.raises(ValidationError):
            ReferenceResource(**ReferenceMapper.map_back(ref)) 
Example #20
Source File: component.py    From gluon-ts with Apache License 2.0 5 votes vote down vote up
def from_hyperparameters(cls: Type[A], **hyperparameters) -> A:
    """
    Reflectively create an instance of a class with a :func:`validated`
    initializer.

    Parameters
    ----------
    cls
        The type ``A`` of the component to be instantiated.
    hyperparameters
        A dictionary of key-value pairs to be used as parameters to the
        component initializer.

    Returns
    -------
    A
        An instance of the given class.

    Raises
    ------
    GluonTSHyperparametersError
        Wraps a :class:`ValidationError` thrown when validating the
        initializer parameters.
    """
    Model = getattr(cls.__init__, "Model", None)

    if not Model:
        raise AttributeError(
            f"Cannot find attribute Model attached to the "
            f"{fqname_for(cls)}. Most probably you have forgotten to mark "
            f"the class initializer as @validated()."
        )

    try:
        return cls(**Model(**hyperparameters).__dict__)  # type: ignore
    except ValidationError as e:
        raise GluonTSHyperparametersError from e 
Example #21
Source File: stats.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def get_user_listening_activity(user_id: int, stats_range: str) -> Optional[UserListeningActivityStat]:
    """Get listening activity in the given time range for user with given ID.

        Args:
            user_id: the row ID of the user in the DB
            stats_range: the time range to fetch the stats for
    """
    with db.engine.connect() as connection:
        result = connection.execute(sqlalchemy.text("""
            SELECT user_id, listening_activity->:range AS {range}, last_updated
              FROM statistics.user
             WHERE user_id = :user_id
            """.format(range=stats_range)), {
            'range': stats_range,
            'user_id': user_id
        })
        row = result.fetchone()

    try:
        return UserListeningActivityStat(**dict(row)) if row else None
    except ValidationError:
        current_app.logger.error("""ValidationError when getting {stats_range} top recordings for user with user_id: {user_id}.
                                 Data: {data}""".format(stats_range=stats_range, user_id=user_id,
                                                        data=json.dumps(dict(row)[stats_range], indent=3)),
                                 exc_info=True)
        return None 
Example #22
Source File: exception_handlers.py    From optimade-python-tools with MIT License 5 votes vote down vote up
def validation_exception_handler(request: Request, exc: ValidationError):
    status = 500
    title = "ValidationError"
    errors = set()
    for error in exc.errors():
        pointer = "/" + "/".join([str(_) for _ in error["loc"]])
        source = ErrorSource(pointer=pointer)
        code = error["type"]
        detail = error["msg"]
        errors.add(
            OptimadeError(
                detail=detail, status=status, title=title, source=source, code=code
            )
        )
    return general_exception(request, exc, status_code=status, errors=list(errors)) 
Example #23
Source File: entity.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def create_messages(data, entity: str, stats_range: str, from_ts: int, to_ts: int) -> Iterator[Optional[UserEntityStatMessage]]:
    """
    Create messages to send the data to the webserver via RabbitMQ

    Args:
        data (iterator): Data to sent to the webserver
        entity: The entity for which statistics are calculated, i.e 'artists',
            'releases' or 'recordings'
        stats_range: The range for which the statistics have been calculated
        from_ts: The UNIX timestamp of start time of the stats
        to_ts: The UNIX timestamp of end time of the stats

    Returns:
        messages: A list of messages to be sent via RabbitMQ
    """
    for entry in data:
        _dict = entry.asDict(recursive=True)
        try:
            model = UserEntityStatMessage(**{
                'musicbrainz_id': _dict['user_name'],
                'type': 'user_entity',
                'stats_range': stats_range,
                'from_ts': from_ts,
                'to_ts': to_ts,
                'data': _dict[entity],
                'entity': entity,
                'count': len(_dict[entity])
            })
            result = model.dict(exclude_none=True)
            yield result
        except ValidationError:
            current_app.logger.error("""ValidationError while calculating {stats_range} top {entity} for user: {user_name}.
                                     Data: {data}""".format(stats_range=stats_range, entity=entity, user_name=_dict['user_name'],
                                                            data=json.dumps(_dict, indent=3)),
                                     exc_info=True)
            yield None 
Example #24
Source File: test_job_model.py    From asgard-api with MIT License 5 votes vote down vote up
def test_invalid_job_name_with_slash(self):
        with self.assertRaises(ValidationError):
            self.required_fields_scheduled_job["id"] = "my/app"
            ScheduledJob(**self.required_fields_scheduled_job) 
Example #25
Source File: test_job_model.py    From asgard-api with MIT License 5 votes vote down vote up
def test_invalid_job_name(self):
        with self.assertRaises(ValidationError):
            self.required_fields_scheduled_job["id"] = "InvalidJobName"
            ScheduledJob(**self.required_fields_scheduled_job) 
Example #26
Source File: test_apps_resource.py    From asgard-api with MIT License 5 votes vote down vote up
def test_it_raises_a_validation_error_if_type_is_invalid(self):
        apps = [
            dict(
                type="XABLAU",
                id="sieve_infra_asgard_async-api.7e5d20eb-248a-11e9-91ea-024286d5b96a",
                source="sieve_infra_asgard_async-api.7e5d20eb-248a-11e9-91ea-024286d5b96a",
                framework_id="27b52920-3899-4b90-a1d6-bf83a87f3612-0000",
            )
        ]
        with self.assertRaises(ValidationError):
            AppsResource(apps=apps) 
Example #27
Source File: model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _add_filenames(e: ValidationError, filename):
    def _recursively_add_filenames(l):
        processed = False
        if isinstance(l, Sequence):
            for e in l:
                _recursively_add_filenames(e)
            processed = True
        elif isinstance(l, ErrorWrapper):
            l._loc = (filename, l._loc)

            processed = True
        assert processed, f"Should have processed by now {l}, {repr(l)}"

    _recursively_add_filenames(e.raw_errors) 
Example #28
Source File: model_parser.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse_obj(cls, data: [dict, list], path: str = None):
        "Parse a structured dict or list into Model objects"
        try:
            return super().parse_obj(data)
        except ValidationError as e:
            _add_filenames(e, path)
            raise e 
Example #29
Source File: test_config.py    From QCEngine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_config_validation(opt_state_basic):
    with pytest.raises(pydantic.ValidationError):
        config = qcng.config.get_config(hostname="something", local_options={"bad": 10}) 
Example #30
Source File: domains.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def create_domain_monitor_task(
    db: Session = Depends(get_db),
    *,
    monitor_profile: DomainMonitorSchema
):
    if crud_domain_task.exists(db_session=db, domain_id=monitor_profile.domain_id):
        raise ValidationError(
            [ErrorWrapper(Exception('domain is already under monitor'), loc="domain_id")],
            model=DomainMonitorSchema,
        )

    monitor_task_obj = crud_domain_task.create(db_session=db, obj_in=monitor_profile, serializer=None)
    return dict(result=monitor_task_obj)