티스토리 뷰

728x90
반응형

목차

     

     

    지난 글에서 모델과 서비스로직을 작성한 뒤 글이 길어져 분리했다.

     

    당연히 지난 글에서 이어지는 이야기이며, 기존 설명은 생략하고 바로 코드로 들어가기로 하자.

     

    comment_router.py

     

     

    from fastapi import APIRouter, Depends
    from sqlalchemy.orm import Session
    from models.comment import CommentCreate, CommentUpdate, CommentResponse
    from services import comment_service, auth_service
    from config.db import get_db
    from typing import List
    
    router = APIRouter()
    
    
    @router.post("/create", response_model=CommentResponse)
    def create_comment(
        comment: CommentCreate,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):
        return comment_service.create_comment(db, comment, email)
    
    
    @router.get("/feed/{feed_id}", response_model=List[CommentResponse])
    def get_comments_by_feed_id(feed_id: int, db: Session = Depends(get_db)):
        return comment_service.get_comment_by_feed_id(db, feed_id)
    
    
    @router.patch("/update/{comment_id}", response_model=CommentResponse)
    def update_comment(
        comment_id: int,
        comment: CommentUpdate,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):
        return comment_service.update_comment(db, comment_id, comment, email)
    
    
    @router.delete("/delete/{comment_id}")
    def delete_comment(
        comment_id: int,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):
        comment_service.delete_comment(db, comment_id, email)
        return {"message": "Comment Deleted"}

    코멘트 라우트 모듈의 전부이다.

     

    계층 간 관심사 분리를 위해서 가능한 모든 비즈니스 로직을 서비스 레이어에 위치시켰고,

     

    라우팅 함수에는 의존성 주입을 이용한 세션 생성과 인증 이메일 조회 로직, 그리고 비즈니스 로직 호출만 남겨두었다.

     

    위에서부터 하나씩 살펴보자.

    @router.post("/create", response_model=CommentResponse)
    def create_comment(
        comment: CommentCreate,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):
        return comment_service.create_comment(db, comment, email)

    가장 먼저 코멘트 생성 함수이다.

    @router.post("/create", response_model=CommentResponse)

    위에서 생성한 APIRouter 객체를 이용해 "/create" 엔드포인트로 POST 요청을 보내는 데코레이터를 작성한다.

    def create_comment(

    해당 엔드포인트로 올바른 요청이 들어오면 함수가 호출된다.

        comment: CommentCreate,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):

    해당 함수는 CommentCreate 객체와

     

    db 변수에 할당된 Session객체(여기서 의존성 주입을 이용해 get_db 함수를 호출한다),

     

    그리고 email 변수(여기서도 의존성 주입을 위해 인증 객체에서 이메일을 가지고 온다)를 매개변수로 가진다.

        return comment_service.create_comment(db, comment, email)

    끝으로 주어진 매개변수를 비즈니스로직으로 넘겨주고, 리턴 값을 받아 반환한다.

     

    여기서 CommentResponse에 맞춘 리턴은 서비스로직에서 리턴하도록 처리해 두었기 때문에

     

    특별하게 처리해 줄 필요는 없다.

    @router.get("/feed/{feed_id}", response_model=List[CommentResponse])
    def get_comments_by_feed_id(feed_id: int, db: Session = Depends(get_db)):
        return comment_service.get_comment_by_feed_id(db, feed_id)

    다음으로 피드 번호를 이용해 해당 피드의 코멘트를 전부 가져오는 로직이다.

     

    마찬가지로 데코레이터를 이용해 엔드포인트와 메서드를 정해준다.

     

    이후 Pathvariable로 feed_id를 받고, 의존성 주입을 이용해 Session 객체를 생성해 db에 할당한다.

     

    이어서 서비스 로직을 호출하고, 끝이다.

    @router.patch("/update/{comment_id}", response_model=CommentResponse)
    def update_comment(
        comment_id: int,
        comment: CommentUpdate,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):
        return comment_service.update_comment(db, comment_id, comment, email)

    계속해서 코멘트 업데이트 로직이다.

     

    위의 로직들과 크게 다른 것 없이 데코레이터, 매개변수 설정, 서비스 로직 호출로 이루어져 있다.

    @router.delete("/delete/{comment_id}")
    def delete_comment(
        comment_id: int,
        db: Session = Depends(get_db),
        email: str = Depends(auth_service.get_current_user_authorization),
    ):
        comment_service.delete_comment(db, comment_id, email)
        return {"message": "Comment Deleted"}

    마지막으로 삭제 로직.

     

    전부 똑같지만 삭제가 제대로 되었다는 것을 알리기 위해 리턴값을 문자열로 지정해 주었다.

     

    main.py

     

     

    from fastapi import FastAPI
    from sqlalchemy import create_engine
    from models.user import Base as UserBase  # User의 Base 클래스
    from models.feed import Base as FeedBase  # Feed의 Base 클래스
    from models.comment import Base as CommentBase  # Comment의 Base
    from routers import auth_router, feed_router, comment_router
    
    DATABASE_URL = "sqlite:///./test.db"
    engine = create_engine(DATABASE_URL)
    
    UserBase.metadata.create_all(bind=engine)
    FeedBase.metadata.create_all(bind=engine)
    CommentBase.metadata.create_all(bind=engine)
    
    app = FastAPI()
    
    app.include_router(auth_router.router, prefix="/api/auth", tags=["auth"])
    app.include_router(feed_router.router, prefix="/api/feed", tags=["feed"])
    app.include_router(comment_router.router, prefix="/api/comment", tags=["comment"])
    
    
    @app.get("/")
    def read_root():
        return {"message": "Hello, World!"}

    마지막의 마지막으로 main.py 모듈이다.

     

    Comment의 Base를 가져와 테이블 생성 로직을 작성하고,

     

    FastAPI 앱 객체인 app에 코멘트 라우터의 prefix와 tags를 지정한다.

     

    여기서 tags의 의미 역시 지난 글에서 설명했기 때문에 생략한다.

     

    Summary

     

    이렇게 해서 피드, 사진 업로드, 코멘트의 구현까지 끝이 났다.

     

    다음 구현은 무엇을 해볼지 아직 생각하지 못했지만,

     

    FastAPI에 익숙해지려면 무엇을 할 수 있을지 생각을 더 해보아야 하겠다.

     

    어쨌거나 코멘트 작성 로직, 끝!

    반응형
    댓글
    공지사항
    최근에 올라온 글
    최근에 달린 댓글
    Total
    Today
    Yesterday
    링크
    «   2024/06   »
    1
    2 3 4 5 6 7 8
    9 10 11 12 13 14 15
    16 17 18 19 20 21 22
    23 24 25 26 27 28 29
    30
    글 보관함