当前位置: 首页>>代码示例>>Python>>正文


Python pydantic.ValidationError方法代码示例

本文整理汇总了Python中pydantic.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python pydantic.ValidationError方法的具体用法?Python pydantic.ValidationError怎么用?Python pydantic.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pydantic的用法示例。


在下文中一共展示了pydantic.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: broad_exception_handler

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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 
开发者ID:JoMingyu,项目名称:Flask-Large-Application-Example,代码行数:23,代码来源:error.py

示例2: create_resource

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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="添加成功")


### 修改 
开发者ID:opendevops-cn,项目名称:codo-admin,代码行数:18,代码来源:resource_model.py

示例3: resource_user

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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="修改成功")


### 根据用户昵称查询所有有权限资源 
开发者ID:opendevops-cn,项目名称:codo-admin,代码行数:19,代码来源:resource_model.py

示例4: from_es

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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) 
开发者ID:QwantResearch,项目名称:idunn,代码行数:25,代码来源:recycling.py

示例5: raw_autocomplete

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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") 
开发者ID:QwantResearch,项目名称:idunn,代码行数:26,代码来源:bragi_client.py

示例6: purchase_domain

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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) 
开发者ID:QAX-A-Team,项目名称:LuWu,代码行数:22,代码来源:domains.py

示例7: model_wrapper

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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 
开发者ID:MolSSI,项目名称:QCEngine,代码行数:26,代码来源:util.py

示例8: validate_data

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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 
开发者ID:SFDO-Tooling,项目名称:CumulusCI,代码行数:21,代码来源:model_parser.py

示例9: validate_input

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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 
开发者ID:b2wdigital,项目名称:asgard-api,代码行数:24,代码来源:jobs.py

示例10: test_it_raises_a_validation_error_if_type_is_invalid

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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) 
开发者ID:b2wdigital,项目名称:asgard-api,代码行数:18,代码来源:test_agents_resource.py

示例11: __setattr__

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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) 
开发者ID:dr-leo,项目名称:pandaSDMX,代码行数:24,代码来源:util.py

示例12: test_simple_relationships

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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) 
开发者ID:Materials-Consortia,项目名称:optimade-python-tools,代码行数:19,代码来源:test_entries.py

示例13: test_advanced_relationships

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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) 
开发者ID:Materials-Consortia,项目名称:optimade-python-tools,代码行数:27,代码来源:test_entries.py

示例14: test_bad_links

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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 
开发者ID:Materials-Consortia,项目名称:optimade-python-tools,代码行数:21,代码来源:test_links.py

示例15: get_current_user

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import ValidationError [as 别名]
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 
开发者ID:tiangolo,项目名称:full-stack-fastapi-postgresql,代码行数:19,代码来源:deps.py


注:本文中的pydantic.ValidationError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。