728x90

소스코드

import time
import asyncio
from fastapi import FastAPI

app = FastAPI()

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

# FastAPI는 async를 사용하지 않아도 비동기로 작업을 수행
# https://tigris-data-science.tistory.com/entry/FastAPI%EC%9D%98-%EB%8F%99%EA%B8%B0-%ED%95%A8%EC%88%98-%EB%8F%99%EC%9E%91-%EB%B0%A9%EC%8B%9D
@app.get("/sleep") # API처리중에 다른API 처리가능
def time_sleep():
    time.sleep(5)
    return 5

# async를 사용하면 메인쓰레드에서 동작하여 cpu-bound 작업 수행 시 다른 쓰레드 Blocking됨
@app.get("/async-sleep") # API처리 끝날때까지 다른API block
async def async_sleep():
    time.sleep(5)
    return 5

# async를 사용할 땐 메모리 bound작업을 해야 다른 쓰레드가 Blocking되지 않음
@app.get("/async-asyncio-sleep") # API처리중에 다른API 처리가능
async def asyncio_sleep():
    await asyncio.sleep(5)
    return 5

참고 : 개발환경 라이브러리 버전

annotated-types==0.6.0
anyio==4.3.0
click==8.1.7
colorama==0.4.6
fastapi==0.110.0
h11==0.14.0
idna==3.6
pydantic==2.6.2
pydantic_core==2.16.3
sniffio==1.3.1
starlette==0.36.3
typing_extensions==4.10.0
uvicorn==0.27.1

 

728x90

+ Recent posts