728x90
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 확인)
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 |