본문 바로가기
profile_image

Gnuboard6

FastAPI 라우터 구현 가이드

페이지 정보

작성자 이노힐
댓글 0건 조회 12회
작성일 2025-04-08 09:14:16

본문

FastAPI 라우터 구현 가이드

1. 기본 구조

python

Apply to board_new.py

from fastapi import APIRouter, Depends, Query, Form

from typing_extensions import Annotated

router = APIRouter()

2. 의존성 주입 패턴

python

Apply to board_new.py

# 서비스 클래스 의존성 주입

@router.get("/endpoint")

async def endpoint(

    service: Annotated[ServiceClass, Depends(ServiceClass.async_init)],

    # 추가 파라미터들...

):

    pass

3. 라우터 구현 패턴

GET 요청 처리

python

Apply to board_new.py

@router.get("/path")

async def get_endpoint(

    service: Annotated[ServiceClass, Depends(ServiceClass.async_init)],

    param1: str = Query(None),

    param2: int = Query(1, alias="page")

):

    # 1. 데이터 조회

    data = service.get_data(param1, param2)

    # 2. 컨텍스트 구성

    context = {

        "request": service.request,

        "data": data,

        # 추가 컨텍스트...

    }

    # 3. 템플릿 응답 반환

    return templates.TemplateResponse("template.html", context)

POST 요청 처리

python

Apply to board_new.py

@router.post("/path",

            dependencies=[Depends(validate_token),

                        Depends(validate_super_admin)])

async def post_endpoint(

    service: Annotated[ServiceClass, Depends(ServiceClass.async_init)],

    data: list = Form(..., alias="chk_id[]")

):

    # 1. 데이터 처리

    service.process_data(data)

    # 2. 리다이렉트 응답

    url = "/redirect/path"

    query_params = service.request.query_params

    return RedirectResponse(set_url_query_params(url, query_params), 303)

4. 주요 컴포넌트

4.1 의존성 검증

python

Apply to board_new.py

from lib.dependency.dependencies import validate_token, validate_super_admin

@router.post("/path",

            dependencies=[Depends(validate_token),

                        Depends(validate_super_admin)])

4.2 템플릿 설정

python

Apply to board_new.py

from core.template import UserTemplates

from lib.template_functions import get_group_select

templates = UserTemplates()

templates.env.globals["get_group_select"] = get_group_select

4.3 URL 쿼리 파라미터 처리

python

Apply to board_new.py

from lib.common import set_url_query_params

url = "/path"

query_params = service.request.query_params

return RedirectResponse(set_url_query_params(url, query_params), 303)

5. 구현 시 주의사항

  1. 의존성 주입: 서비스 클래스는 항상 Depends를 통해 주입
  1. 파라미터 검증: Query, Form 등을 사용하여 파라미터 타입 검증
  1. 보안: 필요한 엔드포인트에 적절한 의존성 검증 추가
  1. 응답 처리: GET은 템플릿, POST는 리다이렉트 패턴 사용
  1. 에러 처리: 적절한 예외 처리 및 에러 응답 구현

6. 예시 구현

python

Apply to board_new.py

@router.get("/example")

async def example_list(

    service: Annotated[ExampleService, Depends(ExampleService.async_init)],

    category: str = Query(None),

    page: int = Query(1)

):

    # 데이터 조회

    items = service.get_items(category, page)

    total_count = service.get_total_count(category)

    # 컨텍스트 구성

    context = {

        "request": service.request,

        "items": items,

        "total_count": total_count,

        "current_page": page,

        "paging": get_paging(service.request, page, total_count, service.page_rows)

    }

    return templates.TemplateResponse("example/list.html", context)

이 가이드를 따라 FastAPI 라우터를 구현하시면, 일관된 패턴과 구조를 가진 API를 만들 수 있습니다.

댓글목록

등록된 댓글이 없습니다.

댓글쓰기

내용

방문자 집계

  • 오늘 605
  • 어제 646
  • 최대 849
  • 전체 30,146

Copyright © innohealonline.com. All rights reserved.