当前位置:网站首页>Fastapi web framework [pydantic]

Fastapi web framework [pydantic]

2022-06-21 10:40:00 Be more serious

To learn , Make a note .

Starlette,Pydantic And FastAPI The relationship between

  • Python Type tips for type hints
  • Pydantic It's based on Python Type prompt to define data validation , Serialization and documentation ( Use JSON Pattern ) library .
  • Starlette It's a lightweight ASGI frame / tool kit , It's building high performance Asyncio Ideal choice for service .
     Insert picture description here
from datetime import datetime,date
from pydantic import BaseModel,ValidationError, constr
from pathlib import Path
from typing import List, Optional

from sqlalchemy import Column, Integer, String      #ORM
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base

class User(BaseModel):
    id: int     # Required fields 
    name: str = "John Snow"     # Have default values , Fill in the fields 
    signup_ts: Optional[datetime] = None    # Have default values , Fill in the fields 
    friends: List[int] = []     #  The elements in the list are int Type or can be directly converted to int type 

external_data = {
    
    "id": "123",
    "signup_ts": "2022-6-16 11:15",
    "friends": [1,2,"3"]
}

user = User(**external_data)
print(user.name,user.friends)       #  Invoke properties after instantiation 
print(repr(user.signup_ts))         # repr()  Function to convert an object into a form for the interpreter to read .
print(user.dict())

try:
    User(id=1, signup_ts=datetime.today(), friends=[1,2,"not number"])
except ValidationError as e:
    print(e.json())


print(user.dict())
print(user.json())
print(user.copy())      #  Shallow copy 
print(User.parse_obj(obj=external_data))
print(User.parse_raw('{"id": 123, "name": "John Snow1", "signup_ts": "2022-06-16T11:15:00", "friends": [1, 2, 3]}'))

path = Path('pydantic_test.json')
path.write_text('{"id": 123, "name": "John Snow1", "signup_ts": "2022-06-16T11:15:00", "friends": [1, 2, 3]}')
print(User.parse_file(path))

print(user.schema())
print(user.schema_json())

user_data = {
    "id": "error", "name": "John Snow1", "signup_ts": "2022-06-16T11:15:00", "friends": [1, 2, 3]}
print(User.construct(**user_data))      #construct() Create model classes directly without verifying data , Not recommended in construct Method passed in unauthenticated data 

print(User.__fields__.keys())       # View all fields , When defining model classes , All fields are marked with type , The field order will not be disordered 

class Sound(BaseModel):
    sound: str

class Dog(BaseModel):
    birthday: date
    weight: float = Optional[None]
    sound: List[Sound]      # Different dogs have different barks . Recursive model (Recursive Models) It means nesting one by one 

dogs = Dog(birthday=date.today(), weight=6.66, sound=[
    {
    "sound": "wang wang"},
    {
    "sound": "ying ying"}
])
print(dogs.dict())

Base = declarative_base()

class CompanyOrm(Base):
    __tablename__ = 'companies'         # Table name 
    id = Column(Integer, primary_key=True, nullable=False)      # Primary key , Can't be empty 
    public_key = Column(String(20), index=True, nullable=False, unique=True)
    name = Column(String(63), unique=True)
    domains = Column(ARRAY(String(255)))

class CompanyMode(BaseModel):
    id: int
    public_key: constr(max_length=20)
    name: constr(max_length=63)
    domains: List[constr(max_length=255)]

    class Config:
        orm_mode = True

#  Instance of data table model class 
co_orm = CompanyOrm(
    id = 123,
    public_key = 'forbar',
    name = 'Testing',
    domains = ['example.com', 'test.com']
)
print(CompanyMode.from_orm(co_orm))

Study :https://www.bilibili.com/video/BV1iN411X72b?p=7&spm_id_from=pageDriver&vd_source=06af20c53d413fe5fafd741f14bacbf1

原网站

版权声明
本文为[Be more serious]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211022530266.html