반응형
FASTAPI
Pydantic
pydantic module 의 정의
Data validation and settings management using Python type annotations.
pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.
Define how data should be in pure, canonical Python; validate it with pydantic.
내가 정의한 pydantic schema.py 파일
class UserBase(BaseModel):
username: str
class UserCreate(UserBase):
hashed_password: str
class User(UserBase):
id: int
class Config:
orm_mode = True
반응형
base model
pydantic에서 객체를 정의하는 것은 BaseModel에서 상속되는 새 클래스를 만드는 것만큼 간단하다
클래스에서 새 객체를 생성할 때, pydantic은 결과 모델 인스턴스가 모델에 정의된 필드 유형을 준수하도록 보장한다
id : int 유형
username: str(문자열)
hashed_password: str(문자열)
사용예제
@app.get("/auth/user", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
users = get_users(db, skip=skip, limit=limit)
return users
위 함수를 통하여 Users 의 ID 100 번까지의 정보를 불러올 수 있다.
pydantic
장.단점
장-
pydantic 은 타입 Annotation 을 사용한 데이터 검증 도구이다.
빠르다.
쓰기 편리하다.
단-
serializer의 기능을 모두 포함하지는 않는다.
반응형