本文整理匯總了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
示例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="添加成功")
### 修改
示例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="修改成功")
### 根據用戶昵稱查詢所有有權限資源
示例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)
示例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")
示例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)
示例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
示例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
示例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
示例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)
示例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)
示例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)
示例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)
示例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
示例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