FastAPI Prefix 라우팅 - 66

2023. 1. 17. 22:17·Develop/FastAPI
728x90
SMALL
Authentication Routing /  Todo Routing /  Prefix Routing /  External Routing /  Dependencies Routing

 

1. 라우팅 역할

  • 애플리케이션의 구조를 위한 유연한 도구
  • 확장 가능 한 아키텍처를 지원
  • 파일 구조화를 도움

 

2. 구성할 프로젝트 구조

TodoApp
main.py

database.py

models.py
TodoApp/routers TodoApp/company
auth.py todos.py companyapis.py dependencies.py

Prefix 라우팅

현재 디렉토리 구조

 

auth.py 파일 수정

#router = APIRouter()

router = APIRouter(
    prefix="/auth",
    tags=["auth"],
    responses={401: {"user": "Not authorized"}}
)

prefix: auth.py안의 API의 모든 path는 /auth로 시작하게 된다.

tags: auth.py의 라우터는 auth라는 태그를 가진다.

 

todos.py 파일 수정

#router = APIRouter() 기존 값
router = APIRouter(
    prefix="/todos",
    tags=['todos'],
    responses={404: {"description": "Not found"}}
)


#@router.get("/todos/user") 기존 값
@router.get("/user")
async def read_all_by_user(user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if user is None:
        raise get_user_exception()
    return db.query(models.Todos).filter(models.Todos.owner_id == user.get("id")).all()


#@router.get("/{todo_id}") 기존 값
@router.get("/todo/{todo_id}")
async def read_todo(todo_id: int, user:dict = Depends(get_current_user), db: Session = Depends(get_db)):
    if user is None:
        raise get_user_exception()
    todo_model = db.query(models.Todos).filter(models.Todos.id == todo_id).filter(models.Todos.owner_id == user.get("id")).first()
    if todo_model is not None:
        return todo_model
    raise http_exception()

prefix: todos.py안의 API의 모든 path는 /todos로 시작하게 된다.

tags: todos.py의 라우터는 todos라는 태그를 가진다.

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

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

FastAPI Dependencies 라우팅 - 68  (0) 2023.01.17
FastAPI External 라우팅 - 67  (0) 2023.01.17
FastAPI Todo 라우팅(main.py 수정) 확장성 확인 - 65  (0) 2023.01.17
FastAPI 라우팅 역할 및 인증 라우팅- 64  (0) 2023.01.17
FastAPI Create Data for MySQL - 63  (0) 2023.01.15
'Develop/FastAPI' 카테고리의 다른 글
  • FastAPI Dependencies 라우팅 - 68
  • FastAPI External 라우팅 - 67
  • FastAPI Todo 라우팅(main.py 수정) 확장성 확인 - 65
  • FastAPI 라우팅 역할 및 인증 라우팅- 64
동석해요
동석해요
공부하고 싶은게 많은, 사소한 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 Prefix 라우팅 - 66
상단으로

티스토리툴바