인공지능 개발자 수다(유튜브 바로가기) 자세히보기

Fastapi

[FastAPI] 디자인 패턴-미들웨어 패턴(Middleware Pattern) (11-3)

Suda_777 2025. 1. 27. 17:32
반응형

 

1. 미들웨어(Middleware) 란 무엇인가

개념

  • 클라이언트와 서버 사이에서 데이터 요청(Request) 및 응답(Response)을 처리하는 중간 계층
  • HTTP 요청을 처리하거나 응답을 반환하기 전에 실행되는 함수
  • case1 : 요청이 애플리케이션의 특정 라우터에 도달하기 전에 작업을 수행
  • case2 : 응답이 클라이언트에 반환되기 전에 조작하는 데 사용

주요 역할

  • 요청(Request) 처리 전 작업
    • 요청의 유효성을 검사하거나 수정
    • 인증(Authentication) 및 권한 확인(Authorization)
    • 로그 기록(Log)을 남기거나 성능 모니터링
  • 응답(Response) 처리 후 작업
    • 데이터 압축(Gzip 등)
    • 응답 헤더 추가
    • 에러나 예외(Exception)를 클라이언트에 적절히 전달
  • 보안(Security)
    • CORS(Cross-Origin Resource Sharing) 정책 관리
    • CSRF(Cross-Site Request Forgery) 방지
  • 데이터 관리
    • 세션(Session) 관리
    • 데이터베이스 연결 설정 및 해제

 


2. 미들웨어(Middleware) 사용 방법

2.1. 데코레이터로 만들기

  • 미들웨어 정의 : @app.middleware("http") 데코레이터 사용
  • 미들웨어 함수는 반드시 아래 두 가지 매개변수를 가져야 함.
    • `request: Request` :클라이언트로부터 들어온 요청 객체 (Request).
    • `call_next(request)` : 다음 미들웨어 또는 최종 엔드포인트로 요청을 전달하는 함수
  • 마지막으로 response 를 반환함

예시 코드

from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)  # 요청을 다음으로 전달
    process_time = time.time() - start_time
    print(f"Request: {request.method} {request.url} completed in {process_time:.2f}s")
    return response

 

2.2. 클래스로 만들기

1. FastAPI가 Starlette를 기반으로 하기 때문에 Starlette의 BaseHTTPMiddleware 클래스를 상속받는다.

2. dispatch(self, request: Request, call_next) 메서드를를 만든다.

3. call_next 함수의 결과인 response를 반환한다.

from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import FastAPI, Request

class CustomMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # 요청(Request) 전 처리 로직
        print("Before processing the request")
        
        response = await call_next(request)  # 다음 미들웨어 또는 엔드포인트 호출
        
        # 응답(Response) 후 처리 로직
        print("After processing the request")
        
        return response

 

다음으로 미들웨어를 app에 추가해 준다.

# 미들웨어 추가
app.add_middleware(LoggingMiddleware)

 

반응형