Develop/FastAPI
FastAPI Post Request를 통한 DB 저장 - 39
김잠봉
2023. 1. 4. 14:40
728x90
POST를 통해서 데이터베이스에 데이터를 저장해보는 것이 목표
1. DB에 만들 Table(32페이지 참고)의 유효성 검사를 하기 위한 BaseModel 생성
from pydantic import BaseModel, Field
from typing import Optional
class Todo(BaseModel):
title: str
description: Optional[str]
priority: int = Field(gt=0, lt=6, description="The priority must be between 1-5")
complete: bool
2. 데이터를 생성하기 위한 POST 함수 생성
@app.post("/")
async def create_todo(todo: Todo, db: Session = Depends(get_db)):
todo_model = models.Todos()
todo_model.title = todo.title
todo_model.description = todo.description
todo_model.priority = todo.priority
todo_model.complete = todo.complete
db.add(todo_model)
#db.flush()
db.commit()
return {
'status': 201,
'transaction' : 'Successful'
}
※ 코드 해석
- 매개변수로 Todo의 BaseModel을 받고, get_db 함수를 통해 db랑 연결한다.
- DB에 만든 Table 모델을 가져와서 todo_model에 담는다.
- Table 모델의 각각의 컬럼에 데이터를 담는다.
- sqlalchemy의 add 매서드를 통해 todo_model을 insert 해준다.
- add는 하나씩 데이터를 삽입 / add_all는 한 번에 데이터를 삽입
- commit()은 해당 내용을 DB에 적용한다라는 뜻.
- 번외로 flush()는 DB에 적용하기전 중간 단계라고 보면 된다.(DB에 적용 x)
- add -> flush -> commit or add -> commit
3. Swagger 확인
※ Swagger 해석
- 매개변수로 BaseModel을 지정한 형식에 맞게 POST값을 날린다.
- Code 200을 볼 수 있고 POST API에서 return값으로 넣어준 값들을 볼 수 있다.
※ GET요청했을 때 테이블에 저장된 데이터를 볼 수 있다.
728x90
SMALL