FastAPI 테이블 관계 형성하기- 72

2023. 1. 24. 14:38·Develop/FastAPI
728x90
SMALL
Alembic이 아닌 코드 자체에서 Foreign key 설정

 

1. models.py 수정

from sqlalchemy import Boolean, Column, Integer, String, ForeignKey
from database import Base
from sqlalchemy.orm import relationship


class Users(Base):
    __tablename__ = "users"


    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    username = Column(String, unique=True, index=True)
    first_name = Column(String)
    last_name = Column(String)
    hashed_password = Column(String)
    is_active = Column(Boolean, default=True)
    phone_number = Column(String)
    # foreignkey 생성
    address_id = Column(Integer, ForeignKey("address.id"), nullable=True)

    todos = relationship("Todos", back_populates="owner")
    
    #Address 클래스와 관계 생성
    address = relationship("Address", back_populates="user_address")


class Address(Base):
    __tablename__ = "address"

    id = Column(Integer, primary_key=True, index=True)
    address1 = Column(String)
    address2 = Column(String)
    city = Column(String)
    state = Column(String)
    country = Column(String)
    postalcode = Column(String)

    user_address = relationship('Users', back_populates="address")

 

2. router 디렉터리에 address.py 생성

import sys
sys.path.append("..")

from typing import Optional
from fastapi import Depends, APIRouter
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session
from pydantic import BaseModel
from .auth import get_current_user, get_user_exception


router = APIRouter(
    prefix="/address",
    tags=["address"],
    responses={404: {"description":"Not found"}}
)

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

def successful_response(status_code:int):
    return {
        'status': status_code,
        'transaction': 'Successful'
    }

class Address(BaseModel):
    address1: str
    address2: Optional[str]
    city: str
    state: str
    country: str
    postalcode: str

 

3. address.py에 POST API 생성

@router.post("/")
async def create_address(address: Address,
                         user: dict = Depends(get_current_user),
                         db: Session = Depends(get_db)):
    if user is None:
        raise get_user_exception()

    # address 테이블 데이터 생성
    address_model = models.Address()
    address_model.address1 = address.address1
    address_model.address2 = address.address2
    address_model.city = address.city
    address_model.state = address.state
    address_model.country = address.country
    address_model.postalcode = address.postalcode

    db.add(address_model)
    db.flush()

    # user 테이블 데이터 업데이트
    user_model = db.query(models.Users).filter(models.Users.id == user.get("id")).first()
    user_model.address_id = address_model.id

    db.add(user_model)

    db.commit()
    
    return successful_response(200)

 

4. main.py에 router 등록

app.include_router(address.router)

 

5. user token 발행 후 postman 접속

seok 사용자 toekn 발행 

 

6. address 데이터 생성(PostgreSQL 확인)

데이터를 만들고 삭제했기때문에 id가 4인 상태
address_id에 address table id인 4값이 들어간것을 볼 수 있다.

 

728x90
SMALL
저작자표시 비영리 변경금지 (새창열림)

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

FastAPI 프로젝트 진행(시작, HTML 렌더링) - 74  (0) 2023.01.25
FastAPI Alembic 추가 실습하기 - 73  (0) 2023.01.24
FastAPI Alembic new 테이블 및 외래키 생성(Upgrade / Downgrade) - 71  (0) 2023.01.22
FastAPI What is Alembic(upgrade/ downgrade 실습) - 70  (2) 2023.01.22
FastAPI Routing 실습 - 69  (0) 2023.01.18
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI 프로젝트 진행(시작, HTML 렌더링) - 74
  • FastAPI Alembic 추가 실습하기 - 73
  • FastAPI Alembic new 테이블 및 외래키 생성(Upgrade / Downgrade) - 71
  • FastAPI What is Alembic(upgrade/ downgrade 실습) - 70
동석해요
동석해요
공부하고 싶은게 많은, 사소한 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 테이블 관계 형성하기- 72
상단으로

티스토리툴바