本文整理汇总了Python中pydantic.BaseModel方法的典型用法代码示例。如果您正苦于以下问题:Python pydantic.BaseModel方法的具体用法?Python pydantic.BaseModel怎么用?Python pydantic.BaseModel使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pydantic
的用法示例。
在下文中一共展示了pydantic.BaseModel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_openapi_operation_parameters
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def get_openapi_operation_parameters(
*,
all_route_params: Sequence[ModelField],
model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
) -> List[Dict[str, Any]]:
parameters = []
for param in all_route_params:
field_info = get_field_info(param)
field_info = cast(Param, field_info)
# ignore mypy error until enum schemas are released
parameter = {
"name": param.alias,
"in": field_info.in_.value,
"required": param.required,
"schema": field_schema(
param, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore
)[0],
}
if field_info.description:
parameter["description"] = field_info.description
if field_info.deprecated:
parameter["deprecated"] = field_info.deprecated
parameters.append(parameter)
return parameters
示例2: get_openapi_operation_request_body
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def get_openapi_operation_request_body(
*,
body_field: Optional[ModelField],
model_name_map: Dict[Union[Type[BaseModel], Type[Enum]], str],
) -> Optional[Dict]:
if not body_field:
return None
assert isinstance(body_field, ModelField)
# ignore mypy error until enum schemas are released
body_schema, _, _ = field_schema(
body_field, model_name_map=model_name_map, ref_prefix=REF_PREFIX # type: ignore
)
field_info = cast(Body, get_field_info(body_field))
request_media_type = field_info.media_type
required = body_field.required
request_body_oai: Dict[str, Any] = {}
if required:
request_body_oai["required"] = required
request_body_oai["content"] = {request_media_type: {"schema": body_schema}}
return request_body_oai
示例3: compare
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def compare(self, other: Union["ProtoModel", BaseModel], **kwargs) -> bool:
"""Compares the current object to the provided object recursively.
Parameters
----------
other : Model
The model to compare to.
**kwargs
Additional kwargs to pass to ``qcelemental.compare_recursive``.
Returns
-------
bool
True if the objects match.
"""
return compare_recursive(self, other, **kwargs)
示例4: __init__
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def __init__(self, target: BaseModel, allow_failure: bool = True, always_apply: bool = False):
# Checks against already instanced and uninstanced classes while avoiding unhahsable type error
if not always_apply:
if isinstance(target, BaseModel) or (isinstance(target, type) and issubclass(target, BaseModel)):
if (
hasattr(target, self.ALREADY_AUTODOCED_ATTR)
and getattr(target, self.ALREADY_AUTODOCED_ATTR) is True
):
raise AutoDocError(
"Object already has autodoc rules applied to it, cannot re-apply auto documentation"
f"without first resetting the __doc__ attribute and setting "
f"{self.ALREADY_AUTODOCED_ATTR} to False (or deleting it)"
)
else:
raise TypeError("Cannot use auto-doc tech on non-BaseModel subclasses")
self.base_doc = target.__doc__
setattr(target, self.AUTODOC_BASE_DOC_REFERENCE_ATTR, self.base_doc)
self.target = target
setattr(target, self.ALREADY_AUTODOCED_ATTR, True)
self.allow_failure = allow_failure
示例5: initialize_function_and_call
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def initialize_function_and_call(
self,
payload_location: PayloadLocation,
schema: Type[BaseModel] = TestSchema,
json_force_load: bool = False,
):
"""
인자 정보를 통해 `validate_with_pydantic`으로 데코레이팅된 함수를 생성하고, 호출합니다.
"""
@validate_with_pydantic(
payload_location=payload_location,
model=schema,
json_force_load=json_force_load,
)
def handler():
pass
handler()
示例6: search_results_to_model
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def search_results_to_model(
results_from_couchbase: list, *, doc_model: Type[BaseModel]
):
items = []
for doc in results_from_couchbase:
data = doc.get("fields")
if not data:
continue
data_nones = {}
for key, value in data.items():
field: Field = doc_model.__fields__[key]
if not value:
value = None
elif field.shape in {Shape.LIST, Shape.SET, Shape.TUPLE} and not isinstance(
value, list
):
value = [value]
data_nones[key] = value
doc = doc_model(**data_nones)
items.append(doc)
return items
示例7: search_results
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def search_results(
bucket: Bucket,
*,
query_string: str,
index_name: str,
doc_model: Type[BaseModel],
skip=0,
limit=100,
):
doc_results = search_get_results(
bucket=bucket,
query_string=query_string,
index_name=index_name,
skip=skip,
limit=limit,
)
return search_results_to_model(doc_results, doc_model=doc_model)
示例8: search_results_by_type
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def search_results_by_type(
bucket: Bucket,
*,
query_string: str,
index_name: str,
doc_type: str,
doc_model: Type[BaseModel],
skip=0,
limit=100,
):
doc_results = search_get_results_by_type(
bucket=bucket,
query_string=query_string,
index_name=index_name,
doc_type=doc_type,
skip=skip,
limit=limit,
)
return search_results_to_model(doc_results, doc_model=doc_model)
示例9: build_input_model
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def build_input_model(self, data: Union[Dict[str, Any], "BaseModel"], raise_error: bool = True) -> "BaseModel":
"""
Build and validate the input model, passes if the data was a normal BaseModel input.
Parameters
----------
data : Union[Dict[str, Any], 'BaseModel']
A data blob to construct the model from or the input model itself
raise_error : bool, optional
Raise an error or not if the operation failed.
Returns
-------
BaseModel
The input model for the procedure.
"""
示例10: ModelFactory
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def ModelFactory(subclass_marker: Type[BaseModel]):
"""
Função usada apenas para modelos que são abstratos, ou seja,
modelos onde temos múltiplos backends possíveis.
Agent é um exemplo: Podemos ter múltiplos backends para um Agent (Mesos, etc).
Quando o retorno dessa função é usada em um modelo serializável, cada implementação do modelo
deve definit o valor do atributo `type`.
"""
class _ModelFactory(PydanticBaseModel):
def __new__(cls, *args, **kwargs) -> BaseModel:
type_ = kwargs.pop("type")
for subclass in subclass_marker.__subclasses__():
if subclass.__fields__["type"].default == type_:
return subclass(*args, **kwargs) # type: ignore
raise ValueError(
f"'{type_}' is an invalid {subclass_marker} type. "
)
return _ModelFactory
示例11: request
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def request(
self,
method: str,
params: dict,
throw_errors: typing.Optional[bool] = None,
response_model: typing.Optional[BaseModel] = None,
raw_response: bool = False,
) -> typing.Union[dict, BaseModel]:
"""Make a request"""
return await self.api(
method,
params,
throw_errors=throw_errors,
response_model=response_model,
raw_response=raw_response,
)
示例12: sqlalchemy_to_pydantic
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def sqlalchemy_to_pydantic(
db_model: Type, *, exclude: Container[str] = []
) -> Type[BaseModel]:
"""
Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
"""
mapper = inspect(db_model)
fields = {}
for attr in mapper.attrs:
if isinstance(attr, ColumnProperty):
if attr.columns:
column = attr.columns[0]
python_type = column.type.python_type
name = attr.key
if name in exclude:
continue
default = None
if column.default is None and not column.nullable:
default = ...
fields[name] = (python_type, default)
pydantic_model = create_model(
db_model.__name__, **fields # type: ignore
)
return pydantic_model
示例13: test_record
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def test_record() -> None:
record = Record([1, 'dog'], ['id', 'name'])
assert str(record) == '<Record(id=1, name=dog)>'
assert record.headers == ['id', 'name']
assert next(record) == 1
assert next(record) == 'dog'
with pytest.raises(StopIteration):
next(record)
assert record.dict() == {'id': 1, 'name': 'dog'}
class Pet(BaseModel):
id: int
name: str
assert record.model(Pet) == Pet(id=1, name='dog')
assert record == Record([1, 'dog'], ['id', 'name'])
assert record == [1, 'dog']
assert record == (1, 'dog')
assert record != Record([2, 'cat'], ['id', 'name'])
assert record != []
assert record != tuple()
assert record != ''
示例14: test_self_forward_ref_module
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def test_self_forward_ref_module(create_module):
module = create_module(
"""
from pydantic import BaseModel
from pydantic.typing import ForwardRef
Foo = ForwardRef('Foo')
class Foo(BaseModel):
a: int = 123
b: 'Foo' = None
Foo.update_forward_refs()
"""
)
assert module.Foo().dict() == {'a': 123, 'b': None}
assert module.Foo(b={'a': '321'}).dict() == {'a': 123, 'b': {'a': 321, 'b': None}}
示例15: test_self_forward_ref_local
# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseModel [as 别名]
def test_self_forward_ref_local(create_module):
module = create_module(
"""
from pydantic import BaseModel
from pydantic.typing import ForwardRef
def main():
Foo = ForwardRef('Foo')
class Foo(BaseModel):
a: int = 123
b: Foo = None
Foo.update_forward_refs()
return Foo
"""
)
Foo = module.main()
assert Foo().dict() == {'a': 123, 'b': None}
assert Foo(b={'a': '321'}).dict() == {'a': 123, 'b': {'a': 321, 'b': None}}