🌟 Python asyncio 와 FastAPI/Django 비동기 여러 작업 동시 처리 기능 정리
1. ✨ asyncio 또는 “비동기”이 무엇인가?
- asyncio는 Python의 비동기(가능성)을 지원하는 프로그램 라이브러리다.
- 시간이 금강한 작업과 (홀로, API 호출, sleep 기반) 같은 것을 통신에 무리 두고 더 효율적으로 처리할 때 사용한다.
2. 평생적인 복잡한 작업들을 동시에? ❄️ 복잡 사례
예상: 라면을 만들려고 할 때
- 물 깨지기 (3초 걸린다)
- 물 깨지는 동안 가슴, 계란, 구매하기
▶️ 이것이 복잡치로 되게 “비동기”
3. FastAPI와 Django에서 어떻게 연결되는가?
✔️ FastAPI 예제 (asyncio 기능 용어)
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/ramen")
async def make_ramen():
await asyncio.sleep(3) # 3초 기반
return {"msg": "🍜 라면 완전!"}
- async def로 함수를 정의
- await로 asyncio의 작업들를 기반
- FastAPI는 asyncio 기능을 귀여운지도 내부적으로 가지고 있다.
✔️ Django 예제 (3.1+부터 사용 가능, 단 ASGI 필요)
from django.http import JsonResponse
import asyncio
async def make_ramen(request):
await asyncio.sleep(3)
return JsonResponse({"msg": "🍜 라면 완전!"})
- async def로 해당 view 함수 설정
- await 통해 asyncio 기능 발동
- 저작 필요: ASGI 서버 (Uvicorn, Daphne)
4. asyncio.gather 여러 API 동시 호출 예제
import httpx
from fastapi import FastAPI
import asyncio
app = FastAPI()
async def fetch_url(url):
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.text
@app.get("/multi")
async def call_apis():
urls = ["https://example.com", "https://naver.com"]
results = await asyncio.gather(*(fetch_url(url) for url in urls))
return {"data": results}
- 두 개 이상의 API를 동시적으로 호출하고 결과를 모아서 반환
- gather 는 “여러 async 함수를 각각 복잡 수행” 의 그룹지의 한 기능
5. ✨ 정리 Recap
패턴 내용
asyncio | Python의 비동기 가능성 처리 보안 라이브러리 |
async/await | 비동기 함수와 기반을 시간적 바지고 처리 |
FastAPI | asyncio 기능이 기본 통화치이며 async 복잡을 지원 |
Django | 3.1+부터 async 발동을 지원, ASGI서버로 파워가 필요 |
httpx & gather | 외부 API 복잡 호출을 가능하게 해주는 가능성 |
필요하면 asyncio 관련 패턴들을 이어서 (loop, task, awaitable, async DB, Redis등) 정리해줄게!
문의 내주면 계속 연계해 설명해줄게 가능 해 합니다 😊
'기술블로그-Fastapi편' 카테고리의 다른 글
🚨 GitHub Actions actions/cache@v2 오류 발생 원인 및 해결 방법 (0) | 2025.05.26 |
---|---|
🔧 Python 개발 필수 도구 4종 + 커버리지 도구 정리 (Poetry 기준) (0) | 2025.05.26 |
👉 Python 개념 정리: 상수(Constant) 와 리터럴(Literal) (0) | 2025.05.26 |
📅 공공데이터포털 공휴일 API 사용법 총정리 (0) | 2025.05.26 |
✅ isinstance() 함수 완전 정복 (0) | 2025.05.23 |