[python] FastAPI와 Celery를 결합하여 비동기 작업 처리하기

FastAPI는 신속하게 만들어진 웹 API를 구축하기 위한 현대적이고 빠른 프레임워크로서, 비동기 및 병렬 작업을 지원합니다. Celery는 분산 작업 대기열을 처리하기 위한 도구로, 비동기 작업을 간단하게 처리할 수 있습니다. 본 글에서는 FastAPI와 Celery를 결합하여 비동기 작업을 처리하는 방법에 대해 알아보겠습니다.

1. FastAPI 설치

먼저 FastAPI를 설치합니다.

pip install fastapi

2. Celery 설치

그리고 Celery도 설치합니다.

pip install celery

3. FastAPI 애플리케이션 구현

다음으로, FastAPI 애플리케이션을 구현합니다.

from fastapi import FastAPI
import celery

app = FastAPI()

@app.get("/trigger_task/{task_name}")
async def trigger_task(task_name: str):
    # Celery 작업을 실행하는 코드 작성
    return {"message": f"Task '{task_name}' has been triggered"}

4. Celery 작업 정의

그리고 Celery 작업을 정의합니다.

import time
from celery import Celery

app = Celery('tasks', broker='pyamqp://guest@localhost//')

@app.task
def perform_task(task_name):
    # 작업 수행 내용 작성
    time.sleep(5)
    return f"Task '{task_name}' has been completed"

5. Celery 워커 실행

Celery 워커를 실행합니다.

celery -A tasks worker --loglevel=info

6. FastAPI 애플리케이션 실행

마지막으로, FastAPI 애플리케이션을 실행합니다.

uvicorn main:app --reload

이제 FastAPI와 Celery를 결합하여 비동기 작업을 처리할 준비가 되었습니다. 요청이 들어올 때마다 Celery를 사용하여 백그라운드에서 요청에 대한 작업을 수행할 수 있게 되었습니다.

참고 자료: