[FastAPI] BackgroundTasks 사용 시 주의 할 점

_____·2022년 7월 2일
0

FastAPI

목록 보기
8/10
import time
from fastapi import FastAPI, BackgroundTasks
from fastapi.concurrency import run_in_threadpool

app = FastAPI()

@app.get("/")
async def home_page(back_task: BackgroundTasks):
    back_task.add_task(long_task)
    return "async test"

@app.get("/a")
async def home_page():
    return "a page"

async def long_task():
    count =10 
    while count > 0:
        print(f"{count}");
        time.sleep(1)
        count -=1

이 코드는 BackgroundTask에 long_task 함수를 할당 하지만 비동기적으로 처리 되지 않는다. long_task 함수의 내용이 다 처리 될 때 까지 다른 동작은 블락 된다.

BackgroundTask에 등록 할 함수는 동기로 선언해야, starlette이 별도의 스레드에서 실행하게 된다.

import time
from fastapi import FastAPI, BackgroundTasks
from fastapi.concurrency import run_in_threadpool

app = FastAPI()

@app.get("/")
async def home_page(back_task: BackgroundTasks):
    back_task.add_task(long_task)
    return "async test"

@app.get("/a")
async def home_page():
    return "a page"

def long_task():
    count =10 
    while count > 0:
        print(f"{count}");
        time.sleep(1)
        count -=1

<요약>
백그라운드 태스크에 할당 '되는' 쪽은 일반적인 def로 선언 된 함수
백그라운드 태스크에 할당 '하는' 쪽은 async def로 선언된 비동기 함수

profile
개발자입니다.

0개의 댓글