- プロジェクトのセットアップ
pip install fastapi[all] tortoise-orm
- プロジェクト構成
project/
├── app/
│ ├── __init__.py
│ ├── models.py
│ ├── main.py
│ └── config.py
└── requirements.txt
- Tortoise ORMのモデル定義
app/models.py
from tortoise import fields, models
class User(models.Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=100)
class Meta:
table = "users"
4. Tortoise ORMの設定
```python
# app/config.py
from tortoise import Tortoise
async def init():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
modules={'models': ['app.models']}
)
await Tortoise.generate_schemas()
- FastAPIの設定とエンドポイント
# app/main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from app.config import init
from app.models import User
import asyncio
app = FastAPI()
# データベースの初期化
@app.on_event("startup")
async def startup_event():
await init()
@app.on_event("shutdown")
async def shutdown_event():
await Tortoise.close_connections()
# スキーマの定義
class UserCreate(BaseModel):
name: str
@app.post("/users/", response_model=UserCreate)
async def create_user(user: UserCreate):
user_obj = await User.create(name=user.name)
return user_obj
@app.get("/users/{user_id}", response_model=UserCreate)
async def get_user(user_id: int):
user_obj = await User.get(id=user_id)
if not user_obj:
raise HTTPException(status_code=404, detail="User not found")
return user_obj