Python pydantic.BaseModel() Examples
The following are 30
code examples of pydantic.BaseModel().
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: utils.py From fastapi with MIT License | 7 votes |
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
Example #2
Source File: utils.py From fastapi with MIT License | 7 votes |
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
Example #3
Source File: base.py From asgard-api with MIT License | 6 votes |
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
Example #4
Source File: autodocs.py From QCElemental with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #5
Source File: test_forward_ref.py From pydantic with MIT License | 6 votes |
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}}
Example #6
Source File: test_forward_ref.py From pydantic with MIT License | 6 votes |
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}}
Example #7
Source File: test_forward_ref.py From pydantic with MIT License | 6 votes |
def test_missing_update_forward_refs(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 """ ) with pytest.raises(ConfigError) as exc_info: module.Foo(b=123) assert str(exc_info.value).startswith('field "b" not yet prepared so type is still a ForwardRef')
Example #8
Source File: test_validation.py From Flask-Large-Application-Example with MIT License | 6 votes |
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()
Example #9
Source File: basemodels.py From QCElemental with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #10
Source File: test_invalid_sequence_param.py From fastapi with MIT License | 6 votes |
def test_invalid_dict(): with pytest.raises(AssertionError): app = FastAPI() class Item(BaseModel): title: str @app.get("/items/") def read_items(q: Dict[str, Item] = Query(None)): pass # pragma: no cover
Example #11
Source File: test_pydataapi.py From py-data-api with MIT License | 6 votes |
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 != ''
Example #12
Source File: schemas.py From CTFd with Apache License 2.0 | 6 votes |
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
Example #13
Source File: utils.py From full-stack-flask-couchbase with MIT License | 6 votes |
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
Example #14
Source File: utils.py From full-stack-flask-couchbase with MIT License | 6 votes |
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)
Example #15
Source File: utils.py From full-stack-flask-couchbase with MIT License | 6 votes |
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)
Example #16
Source File: model.py From QCEngine with BSD 3-Clause "New" or "Revised" License | 6 votes |
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. """
Example #17
Source File: api.py From vkbottle with MIT License | 6 votes |
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, )
Example #18
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_get_data_type_invalid_obj(): with pytest.raises(ValueError, match='invalid schema object'): parser = OpenAPIParser(BaseModel, CustomRootType) assert parser.get_data_type(JsonSchemaObject())
Example #19
Source File: test_forward_ref.py From pydantic with MIT License | 5 votes |
def test_forward_ref_sub_types(create_module): module = create_module( """ from typing import Union from pydantic import BaseModel from pydantic.typing import ForwardRef class Leaf(BaseModel): a: str TreeType = Union[ForwardRef('Node'), Leaf] class Node(BaseModel): value: int left: TreeType right: TreeType Node.update_forward_refs() """ ) Node = module.Node Leaf = module.Leaf data = {'value': 3, 'left': {'a': 'foo'}, 'right': {'value': 5, 'left': {'a': 'bar'}, 'right': {'a': 'buzz'}}} node = Node(**data) assert isinstance(node.left, Leaf) assert isinstance(node.right, Node)
Example #20
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_get_data_type_array(schema_types, result_types): parser = OpenAPIParser(BaseModel, CustomRootType) assert parser.get_data_type(JsonSchemaObject(type=schema_types)) == [ DataType(type=r) for r in result_types ]
Example #21
Source File: basemodels.py From QCElemental with BSD 3-Clause "New" or "Revised" License | 5 votes |
def json(self, **kwargs): # Alias JSON here from BaseModel to reflect dict changes return self.serialize("json", **kwargs)
Example #22
Source File: test_forward_ref.py From pydantic with MIT License | 5 votes |
def test_self_reference_json_schema(create_module): module = create_module( """ from typing import List from pydantic import BaseModel class Account(BaseModel): name: str subaccounts: List['Account'] = [] Account.update_forward_refs() """ ) Account = module.Account assert Account.schema() == { '$ref': '#/definitions/Account', 'definitions': { 'Account': { 'title': 'Account', 'type': 'object', 'properties': { 'name': {'title': 'Name', 'type': 'string'}, 'subaccounts': { 'title': 'Subaccounts', 'default': [], 'type': 'array', 'items': {'$ref': '#/definitions/Account'}, }, }, 'required': ['name'], } }, }
Example #23
Source File: test_forward_ref.py From pydantic with MIT License | 5 votes |
def test_self_reference_json_schema_with_future_annotations(create_module): module = create_module( """ from __future__ import annotations from typing import List from pydantic import BaseModel class Account(BaseModel): name: str subaccounts: List[Account] = [] Account.update_forward_refs() """ ) Account = module.Account assert Account.schema() == { '$ref': '#/definitions/Account', 'definitions': { 'Account': { 'title': 'Account', 'type': 'object', 'properties': { 'name': {'title': 'Name', 'type': 'string'}, 'subaccounts': { 'title': 'Subaccounts', 'default': [], 'type': 'array', 'items': {'$ref': '#/definitions/Account'}, }, }, 'required': ['name'], } }, }
Example #24
Source File: schema.py From dstc8-meta-dialog with MIT License | 5 votes |
def _asdict(self): # convert to list for json-serializability return dict(domains=self.domains, tasks=self.tasks, paths=self.paths) # the next few fields/functions are here to make PartitionSpec behave like # a pytext ConfigBase object. This way, we can use it directly in a task # config. It would be easier if we could just inherit from ConfigBase, # but alas, ConfigBase's metaclass is not a metaclass of BaseModel.
Example #25
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_get_data_type(schema_type, schema_format, result_type, from_, import_): if from_ and import_: imports_: Optional[List[Import]] = [Import(from_=from_, import_=import_)] else: imports_ = None parser = OpenAPIParser(BaseModel, CustomRootType) assert parser.get_data_type( JsonSchemaObject(type=schema_type, format=schema_format) ) == [DataType(type=result_type, imports_=imports_)]
Example #26
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_parse_object(source_obj, generated_classes): parser = OpenAPIParser(BaseModel, CustomRootType) parser.parse_object('Pets', JsonSchemaObject.parse_obj(source_obj)) assert dump_templates(list(parser.results)) == generated_classes
Example #27
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_parse_array(source_obj, generated_classes): parser = OpenAPIParser(BaseModel, CustomRootType) parser.parse_array('Pets', JsonSchemaObject.parse_obj(source_obj)) assert dump_templates(list(parser.results)) == generated_classes
Example #28
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_openapi_parser_parse(with_import, format_, base_class): parser = OpenAPIParser( BaseModel, CustomRootType, text=Path(DATA_PATH / 'api.yaml').read_text(), base_class=base_class, ) expected_file = get_expected_file( 'openapi_parser_parse', with_import, format_, base_class ) assert ( parser.parse(with_import=with_import, format_=format_) == expected_file.read_text() )
Example #29
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_openapi_parser_parse_resolved_models(): parser = OpenAPIParser( BaseModel, CustomRootType, text=Path(DATA_PATH / 'resolved_models.yaml').read_text(), ) assert ( parser.parse() == ( EXPECTED_OPEN_API_PATH / 'openapi_parser_parse_resolved_models' / 'output.py' ).read_text() )
Example #30
Source File: test_openapi.py From datamodel-code-generator with MIT License | 5 votes |
def test_parse_root_type(source_obj, generated_classes): parser = OpenAPIParser(BaseModel, CustomRootType) parser.parse_root_type('Name', JsonSchemaObject.parse_obj(source_obj)) assert dump_templates(list(parser.results)) == generated_classes