본문 바로가기
FastAPI tips

Middleware 커스텀해서 사용하기

by 스티브 십잡스 2024. 5. 3.
from fastapi import FastAPI

from middlewares import CustomMiddleware

app = FastAPI()

app.add_middleware(CustomMiddleware) # 미들웨어 추가
  • middlewares.py
    from starlette.types import ASGIApp, Receive, Scope, Send
    
    
    class CustomMiddleware:
        def __init__(self, app: ASGIApp) -> None:
            self.app = app
    
        async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
    	# do something
            await self.app(scope, receive, send)
            # do something

API 요청이 오면, 미들웨어를 거치고 엔드포인트에 클라이언트의 요청이 온다.

그 사이에 미들웨어에서 처리할 수 있는 처리들이 있다.

예로 파이썬의 structlog 라이브러리를 사용할 때, Trace Id를 uuid로 미들웨어에서 설정할 수 있다.

 

참고 글

 

FastAPI can not use request body in middleware / 미들웨어에서 request body 사용 불가 / FastAPI(starlette) AGSI flow

starlette는 경량 ASGI를 구현할 수 있는 웹프레임워크이며, FastAPI는 starlette를 wraping하여 http 서비스(웹 혹은 API)를 간단하게 만들 수 있는 웹프레임워크입니다. https://www.starlette.io/ Starlette ✨ The littl

asung123456.tistory.com

 

'FastAPI tips' 카테고리의 다른 글

Jinja2 템플릿 활용  (0) 2024.05.08
Excel 다운로드 API  (0) 2024.05.08
UploadFile, 이미지 form-data  (0) 2024.03.28
Request에서 form-data, query-string 가져오기  (0) 2024.03.28