当前位置:网站首页>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 .

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
边栏推荐
猜你喜欢

Simple Android weather app (III) -- city management and database operation

字符串

Optimisation des performances - compression, chargement et formatage des images

Ccs7.3 how to erase only part of the flash sector when burning DSP on-chip flash (two projects of on-chip flash burning of a DSP chip)

The third part of the procedure

WCF RestFul+JWT身份验证

Brief introduction of quality control conditions before genotype filling

JS regular - comb

Matplotlib two methods of drawing torus!

Three elements of basic concepts and methods of machine learning
随机推荐
Audio and video format introduction, encoding and decoding, audio and video synchronization
About Alipay - my savings plan - interest rate calculation instructions
字符串
character string
JobService的使用
Odd number of characters异常
Simple Android weather app (III) -- city management and database operation
Embedded remote post, part-time job, order receiving, crowdsourcing platform
金融机构抢滩“数字员工”;保险APP适老化服务评测框架发布
送分题,ArrayList 的扩容机制了解吗?
知识点滴 - 什么是加速移动网页(AMP)?
Celsius 的暴雷,会是加密领域的“雷曼时刻”吗?
The execution process before executing the main function after the DSP chip is powered on
注解的定义以及注解编译器
聊聊大火的多模态项目
中部“第一城”,网安长沙以何安网?
The bilingual live broadcast of Oriental selection is popular, and the transformation of New Oriental is beginning to take shape
Application configuration management, basic principle analysis
Signal power spectrum estimation
cvte一面