비동기 엔드포인트와 데이터베이스 통합
비동기 경로 처리기를 작성하고 SQLAlchemy로 데이터베이스에 연결합니다.
비동기 엔드포인트와 데이터베이스 통합은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
async def 엔드포인트
차단되지 않는 I/O를 위해 async def로 경로 처리기를 선언합니다. CPU를 많이 사용하거나 차단되는 작업에는 def를 사용합니다(FastAPI가 이러한 작업을 스레드 풀에서 실행합니다).
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/slow")
async def slow():
await asyncio.sleep(1) # non-blocking
return {"done": True}PostgreSQL용 asyncpg
asyncpg는 빠른 비동기 PostgreSQL 드라이버입니다. 요청 전체에서 공유하는 연결 풀을 사용합니다.
# pip install asyncpg
import asyncpg, asyncio
async def main():
pool = await asyncpg.create_pool("postgresql://user:pass@host/db")
async with pool.acquire() as conn:
rows = await conn.fetch("SELECT id, name FROM users")
await pool.close()
return rowsSQLAlchemy 비동기 처리
SQLAlchemy 1.4+와 async_sessionmaker를 사용하면 비동기 ORM을 구현할 수 있습니다. AsyncSession을 FastAPI 의존성으로 사용합니다.
# pip install sqlalchemy aiosqlite
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
engine = create_async_engine("sqlite+aiosqlite:///db.sqlite")
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)
async def get_db():
async with AsyncSessionLocal() as session:
yield session데이터베이스 의존성
FastAPI 의존성에서 세션을 넘겨주어 요청이 끝난 뒤 커밋되고 닫히게 합니다.
from fastapi import Depends, FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
app = FastAPI()
async def get_db():
async with AsyncSessionLocal() as session:
yield session
@app.get("/users")
async def get_users(db: AsyncSession = Depends(get_db)):
result = await db.execute(select(User))
return result.scalars().all()SQLAlchemy ORM 모델
DeclarativeBase로 ORM 모델을 정의하고 데이터베이스 테이블에 매핑합니다.
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase): pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
email: Mapped[str]CRUD 작업
SQLAlchemy 비동기 세션 메서드를 사용해 기본적인 생성, 조회, 수정, 삭제 작업을 구현합니다.
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
async def create_user(db: AsyncSession, name: str, email: str):
user = User(name=name, email=email)
db.add(user)
await db.commit()
await db.refresh(user)
return user
async def get_user(db: AsyncSession, user_id: int):
result = await db.execute(select(User).where(User.id == user_id))
return result.scalar_one_or_none()마이그레이션을 위한 Alembic
Alembic을 사용해 버전 관리 방식으로 데이터베이스 스키마 마이그레이션을 관리합니다.
# pip install alembic
# alembic init alembic
# Edit alembic/env.py to point to your models
# Generate a migration:
# alembic revision --autogenerate -m "add users table"
# Apply:
# alembic upgrade head비동기 HTTP 호출을 위한 httpx
비동기 FastAPI 엔드포인트에서 외부 API를 호출하려면 httpx.AsyncClient를 사용합니다.
# pip install httpx
import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/weather")
async def weather(city: str):
async with httpx.AsyncClient() as client:
r = await client.get(f"https://wttr.in/{city}?format=j1")
return r.json()백그라운드 작업
응답을 보낸 후 작업을 실행하려면 BackgroundTasks를 사용합니다. 예를 들어 이메일을 보내거나 캐시를 업데이트할 수 있습니다.
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def send_welcome_email(email: str):
# blocking I/O — runs in background thread
smtp_send(email, "Welcome!")
@app.post("/register")
def register(email: str, bg: BackgroundTasks):
create_user(email)
bg.add_task(send_welcome_email, email)
return {"status": "registered"}수명 주기 이벤트
lifespan 컨텍스트 관리자를 사용해 시작 및 종료 코드를 실행합니다(FastAPI 0.93+). 예를 들어 데이터베이스 연결 풀을 만들 수 있습니다.
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = await asyncpg.create_pool(DSN)
yield
await app.state.pool.close()
app = FastAPI(lifespan=lifespan)httpx로 FastAPI 테스트하기
서버를 실행하지 않고 FastAPI 엔드포인트를 테스트하려면 httpx.AsyncClient와 ASGITransport를 사용합니다.
import pytest, httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/ping")
async def ping(): return {"pong": True}
@pytest.mark.asyncio
async def test_ping():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://test"
) as client:
r = await client.get("/ping")
assert r.json() == {"pong": True}빠른 확인
FastAPI 경로 처리기에는 언제 async def를 사용하고 언제 def를 사용해야 합니까?
복습
비동기 데이터베이스 드라이버(asyncpg, SQLAlchemy async)와 함께 async def 엔드포인트를 사용합니다. 데이터베이스 세션을 FastAPI 의존성으로 관리합니다. 응답을 보낸 후의 작업에는 BackgroundTasks를 사용하고, 시작 및 종료 처리에는 lifespan 컨텍스트 관리자를 사용합니다.
자주 묻는 질문
“비동기 엔드포인트와 데이터베이스 통합” 강의는 무료인가요?
네 — “비동기 엔드포인트와 데이터베이스 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“비동기 엔드포인트와 데이터베이스 통합”에서 뭘 배우나요?
비동기 경로 처리기를 작성하고 SQLAlchemy로 데이터베이스에 연결합니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Python Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“비동기 엔드포인트와 데이터베이스 통합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- FastAPI 프로젝트 설정과 첫 엔드포인트
- 경로 매개변수, 쿼리 매개변수 및 요청 본문
- 의존성 주입과 인증
- 비동기 엔드포인트와 데이터베이스 통합