FastAPI 데이터베이스에 유저 데이터 저장하기 - 46

2023. 1. 7. 18:27·Develop/FastAPI
728x90
SMALL
앞서 POST API에서 다뤘던 저장은 데이터베이스 저장이 아니었기에 이번장은 데이터베이스에 데이터를 저장해 보자

 

1. DB에 연결하기 위한 라이브러리 import

from sqlalchemy.orm import Session
from database import SessionLocal, engine
#Depends 추가
from fastapi import FastAPI, Depends

 

2. Base를 상속받은 모든 클래스들을 데이터베이스 내에 테이블로 만든다.

models.Base.metadata.create_all(bind=engine)

 

3. DB를 연결할 수 있는 함수 생성

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

※ return대신 yield를 사용한 이유

return을 사용하게 되면 하나의 session으로 모든 것을 다루게 되고 yield를 사용하게 되면 요청할 때의 session을 사용할 수 있다.

https://stackoverflow.com/questions/64763770/why-we-use-yield-to-get-sessionlocal-in-fastapi-with-sqlalchemy

 

4. POST API 수정

@app.post("/create/user")
async def create_new_user(create_user: CreateUser, db: Session = Depends(get_db)):
    create_user_model = models.Users()
    create_user_model.email = create_user.email
    create_user_model.username = create_user.username
    create_user_model.first_name = create_user.first_name
    create_user_model.last_name = create_user.last_name

    hash_password = get_password_hash(create_user.password)

    create_user_model.hashed_password = hash_password
    create_user_model.is_active = True

    db.add(create_user_model)
    #db.flush(
    db.commit()

 

5. Swagger 확인

유저 데이터를 생성한다. Response body가 null인 이유는 API가 return 해주는 값이 없기 때문이다.

데이터가 잘 저장되었는지 6번에서 확인해 보자

 

6. 터미널로 데이터베이스 확인

users 테이블을 조회했을 때 저장했던 데이터를 확인할 수 있다.

728x90
SMALL
저작자표시 비영리 변경금지

'Develop > FastAPI' 카테고리의 다른 글

FastAPI JSON Web Token(JWT) 생성 - 48  (0) 2023.01.08
FastAPI 사용자 인증 - 47  (0) 2023.01.07
FastAPI bcrypt 비밀번호 암호화 - 45  (0) 2023.01.07
FastAPI Create Authentication & Post Request - 44  (0) 2023.01.07
FastAPI Create Users Table / Create Foreign Key - 43  (0) 2023.01.07
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI JSON Web Token(JWT) 생성 - 48
  • FastAPI 사용자 인증 - 47
  • FastAPI bcrypt 비밀번호 암호화 - 45
  • FastAPI Create Authentication & Post Request - 44
동석해요
동석해요
공부하고 싶은게 많은, 사소한 IT 지식들 공유
    250x250
  • 동석해요
    개발로 자기계발
    동석해요
  • 전체
    오늘
    어제
    • 분류 전체보기 (226)
      • Develop (126)
        • 기초지식 (12)
        • FastAPI (102)
        • Django (11)
      • Database & Data (62)
        • 기초지식 (16)
        • MySQL (29)
        • PostgreSQL (8)
        • 데이터 분석 (9)
      • 인공지능 (11)
        • PyTorch (9)
      • Cloud (8)
        • AWS (4)
        • GCP (2)
      • 버그처리 (14)
      • 회고 & 일상 (5)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
동석해요
FastAPI 데이터베이스에 유저 데이터 저장하기 - 46
상단으로

티스토리툴바