본문 바로가기
C.W.K.
Stream
Lesson 07 of 10 · published

FastAPI + aiosqlite 아키텍처

~14 min · fastapi, architecture, real-world

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

진짜 제품까지 가는 전체 그림

조각을 다 맞춰보자. aiosqlite를 쓰는 진짜 FastAPI 서비스는 결국 다섯 층으로 정리돼.

  1. Lifespan — 뜰 때 store를 열고 내려갈 때 닫아.
  2. Store — aiosqlite를 감싼 CRUD class야. SQL이 사는 유일한 자리지.
  3. Routes — FastAPI endpoint야. Depends로 store를 받아 메서드를 부르고 Pydantic model을 돌려줘.
  4. Models — request와 response 모양을 잡는 Pydantic schema야.
  5. Background task — 오래 걸리는 일, 예를 들어 embedding을 만들거나 인덱싱하는 건 asyncio.create_task나 작업 큐로 빼. request와 response 경로에는 두지 마.
Self-reference: 피파 backend가 딱 이 모양이야. main.py가 lifespan을 맡고, store/conversations.py가 store를, routes/chat.py가 route를, routes/models.py 계열 파일이 Pydantic schema를, heartbeat scheduler가 오래 사는 백그라운드 task를 맡아.

Code

SQL 대신 store에 기대는 route·python
from fastapi import FastAPI, Depends, HTTPException, Request
from pydantic import BaseModel

class MessageIn(BaseModel):
    role: str
    content: str

class MessageOut(BaseModel):
    id: int
    created_at: str

async def store(request: Request) -> 'ConversationStore':
    return request.app.state.store

@app.post('/conversations/{cid}/messages', response_model=MessageOut)
async def post_message(
    cid: int,
    body: MessageIn,
    store: 'ConversationStore' = Depends(store),
):
    return await store.add_message(cid, body.role, body.content)

@app.get('/conversations/{cid}/messages')
async def list_messages(
    cid: int, store: 'ConversationStore' = Depends(store),
):
    return await store.messages_for(cid)

External links

Exercise

미니 피파를 만들어봐. FastAPI에 aiosqlite와 ConversationStore를 얹고 endpoint를 넷 두는 거야. conversation 만들기, conversation 목록, message 올리기, message 목록. lifespan과 dependency와 Pydantic model을 다 연결해. 읽기와 쓰기를 둘 다 때리는 부하 테스트(hey -n 1000 -c 50)를 돌려서 지연이 버티는지 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.