본문 바로가기

FastAPI

미들웨어 - 2

미들웨어 - 1에 이어서 작성해 보겠습니다.

 

미들웨어 - 1에서는 fastapi에 있는 미들 웨어를 사용했는데,

이번에는 미들웨어를 직접 작성해 보겠습니다.

 

main.py 입니다.

 

import time

from fastapi import FastAPI, Request

app = FastAPI()


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


@app.get("/")
async def hello():
    return {"message": "Hello World"}

 

미들웨어는 함수로도 정의할 수 있습니다.

 

위의 코드중에 미들웨어에 해당하는 부분은 이 부분입니다.

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

 

이 함수는 요청과, call_next 즉, 요청을 받고 바로 다음 것(응답)을 받는 call back 함수를 받습니다.

 

request를 받고, call_next 함수를 사용해서 응답을 받습니다. 그리고 받은 응답을 return을 해줍니다.

 

다음 명령어를 실행해서 main.py 파일을 실행해 봅시다.

python main.py

 

HTTPie를 사용해서 요청을 보내 봅시다.

http :8000

 

보낸 요청에 대한 응답 결과는 다음과 같습니다.

content-length: 25
content-type: application/json
date: Tue, 19 Mar 2024 15:25:52 GMT
server: uvicorn
x-process-time: 0.000354766845703125

{
    "message": "Hello World"
}

 

x-process-time 이라는 요청을 받고, 응답을 다시 내보내기까지의 실행 시간도 제대로 출력되었습니다.

 

간단하게 미들웨어를 생성하는 방법에 대해서 알아보았습니다.

 

감사합니다.

'FastAPI' 카테고리의 다른 글

퀴즈봇 만들기 - 2  (0) 2024.04.07
퀴즈봇 만들기 - 1  (0) 2024.03.25
미들웨어 - 1  (0) 2024.03.19
백그라운드 작업 - 2  (0) 2024.03.13
백그라운드 작업 - 1  (2) 2024.03.05