preface
The main way to define objects in pydantic is through models (models inherit BaseModel).
pydantic is mainly a parsing library, not a validation library. Verification is a means to achieve the goal: establish a model that conforms to the types and constraints provided.
In other words, pydantic guarantees the types and constraints of the output model, not the input data.
Although validation is not the primary purpose of pydantic, you can use this library for custom validation.
Basic model usage
User is a model. It has two field IDS, one is an integer, which is required, the other is a string, which is not required (it has a default value)
from pydantic import BaseModel class User(BaseModel): id: int name = 'yo yo'
Type name is inferred from the default value (string), so type comments are not required (but note the warning about field order when some fields do not have type comments)
user = User(id='123')
User this is an instance of user. Object initialization will perform all parsing and validation. If no ValidationError is raised, it indicates that the generated model instance is valid.
The user instance has two attributes: id and name
user = User(id='123') print(user.id) # 123 print(user.name) # yo yo
The fields of the model can be accessed as common properties of user objects. The string '123' has been converted to int according to the field type
name is not set when initializing the user, so it has a default value
So how do you know which required fields are required during initialization? Can pass__ fields_set__ Method
print(user.__fields_set__) # {'id'}
. dict() can convert the attributes of the user object into dictionary format for output, and dict(user) is also equivalent
print(user.dict()) # {'id': 123, 'name': 'yo yo'} print(dict(user)) # {'id': 123, 'name': 'yo yo'}
. json() can convert the attributes of the user object into json format output
print(user.json()) # {"id": 123, "name": "yo yo"}
BaseModel model properties
The above example is just the tip of the iceberg showing what the model can do. The model has the following methods and properties:
dict() returns a dictionary of model fields and values; see. Export model
json() returns a JSON string representing dict(); see. Export model
copy() returns a copy of the model (shallow copy by default); see. Export model
parseobj() a utility for loading any object into a model with error handling if the object is not a dictionary; see. auxiliary function
parseraw() is a utility for loading strings of various formats; see. auxiliary function
parsefile() likes parseraw(), but for file paths; see. auxiliary function
fromorm() loads data from any class into the model; see. ORM mode
schema() returns the dictionary that represents the model as JSON Schema; see. Schema
schemajson() returned by schema(); For the JSON string representation of. Schema
construct() creates the class method of the model without running verification; see. Create a model without validation
`__ fields_set the field name set when initializing the model instance__ Fields Dictionary of model fields__ config ` configuration class of the model, cf. Model configuration
Recursive model
You can use the model itself as a type in the annotation to define a more complex hierarchical data structure.
from typing import List from pydantic import BaseModel class Foo(BaseModel): count: int size: float = None class Bar(BaseModel): apple = 'x' banana = 'y' class Spam(BaseModel): foo: Foo bars: List[Bar] m = Spam(foo={'count': 4}, bars=[{'apple': 'x1'}, {'apple': 'x2'}]) print(m) #> foo=Foo(count=4, size=None) bars=[Bar(apple='x1', banana='y'), #> Bar(apple='x2', banana='y')] print(m.dict()) """ { 'foo': {'count': 4, 'size': None}, 'bars': [ {'apple': 'x1', 'banana': 'y'}, {'apple': 'x2', 'banana': 'y'}, ], } """
auxiliary function
Pydantic provides three classmethod auxiliary functions for the model of parsing data:
-
parseobj: This is very similar to the model approach_ init, except that it requires a dictionary instead of a keyword parameter.
ValidationError is thrown if the object passed is not dict.
-
parse_raw:
This requires a str or bytes, parses it into json, and passes the result to parse_obj. Parsing kimchi data is also supported by properly setting parameters.
content_type
-
parse_file: This requires a file path to read the file and pass the content to parse_raw. If content_ If type is omitted, it is inferred from the extension of the file.
parse_ Use of obj
from datetime import datetime from pydantic import BaseModel, ValidationError class User(BaseModel): id: int name = 'John Doe' signup_ts: datetime = None m = User.parse_obj({'id': 123, 'name': 'James'}) print(m) # id=123 signup_ts=None name='James'
parse_raw requires a str or bytes and resolves it to json
m = User.parse_raw('{"id": 123, "name": "James"}') print(m) # > id=123 signup_ts=None name='James'
parse_file can read the contents of a file
data.json file
from pathlib import Path path = Path('data.json') # Read file contents m = User.parse_file(path) print(m) # > id=123 signup_ts=None name='James'
.write_text() can write its own content to the file
from pathlib import Path path = Path('data1.json') path.write_text('{"id": 345, "name": "James 11"}') m = User.parse_file(path) print(m) # > id=345 name='James 11'
The following is the supporting materials. For friends who do [software testing], it should be the most comprehensive and complete war preparation warehouse. This warehouse has also accompanied me through the most difficult journey. I hope it can also help you!
Finally, it can be in the official account: programmer Hao! Get a 216 page interview document of Software Test Engineer for free. And the corresponding video learning tutorials for free!, It includes basic knowledge, Linux essentials, Shell, Internet program principles, Mysql database, special topics of packet capture tools, interface test tools, test advanced Python programming, Web automation test, APP automation test, interface automation test, advanced continuous integration of test, test architecture, development test framework, performance test, security test, etc.
If my blog is helpful to you and you like my blog content, please click "like", "comment" and "collect" for three times! Friends who like software testing can join our testing technology exchange group: 779450660 (there are various software testing resources and technical discussions)