ASGI (Asynchronous Server Gateway Interface)
Python 웹 서버와 웹 애플리케이션 사이의 비동기 표준 인터페이스. WSGI의 후속 스펙으로, HTTP뿐 아니라 WebSocket, HTTP/2 등 장수명 연결을 지원한다.
WSGI vs ASGI
| WSGI | ASGI |
|---|
| 풀네임 | Web Server Gateway Interface | Asynchronous Server Gateway Interface |
| 동기/비동기 | 동기 only | 동기 + 비동기 |
| 프로토콜 | HTTP 1.1 | HTTP, WebSocket, HTTP/2 |
| 요청 모델 | 1 요청 = 1 스레드/프로세스 | 1 이벤트 루프에서 다수 요청 처리 |
| PEP | PEP 3333 (2003) | ASGI spec (2018~) |
동작 구조
클라이언트 → 웹 서버(Nginx) → ASGI 서버 → Python 앱
│
Uvicorn / Daphne / Hypercorn
- WSGI 서버: Gunicorn, uWSGI — 동기 요청만 처리
- ASGI 서버: Uvicorn, Daphne, Hypercorn — async/await 네이티브 지원
인터페이스 시그니처
# WSGI — 동기 함수
def application(environ, start_response):
start_response("200 OK", [("Content-Type", "text/plain")])
return [b"Hello"]
# ASGI — async 함수, 3개의 파라미터
async def application(scope, receive, send):
await send({
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/plain"]],
})
await send({
"type": "http.response.body",
"body": b"Hello",
})
| 파라미터 | 역할 |
|---|
scope | 연결 메타데이터 (type, path, headers 등) |
receive | 클라이언트로부터 이벤트 수신 |
send | 클라이언트로 이벤트 전송 |
프레임워크별 지원
| 프레임워크 | WSGI | ASGI |
|---|
| Django (3.0+) | ✅ 기본 | ✅ asgi.py 제공 |
| Flask | ✅ 기본 | ❌ (async view는 가능하나 ASGI 아님) |
| FastAPI | ❌ | ✅ ASGI 네이티브 |
| Starlette | ❌ | ✅ ASGI 네이티브 |
| Saleor | — | ✅ Django ASGI + Uvicorn |
Django에서의 ASGI
Django는 3.0부터 ASGI를 지원하지만 ORM이 동기 기반이라 sync_to_async 래퍼가 필요하다. Saleor는 Uvicorn을 ASGI 서버로 사용하여 GraphQL 요청을 처리한다.
# project/asgi.py
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
application = get_asgi_application()
# 실행
uvicorn project.asgi:application --host 0.0.0.0 --port 8000
관련 문서