在FastAPI中使用ORM,一般情況下會使用SQLAlchemy作為ORM框架。以下是一個簡單的示例:
pip install sqlalchemy
pip install databases
pip install psycopg2
from databases import Database
from sqlalchemy import create_engine
DATABASE_URL = "sqlite:///./test.db"
database = Database(DATABASE_URL)
# 創建數據庫引擎
engine = create_engine(DATABASE_URL)
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
email = Column(String, unique=True)
from sqlalchemy.orm import sessionmaker
# 創建數據庫表
Base.metadata.create_all(engine)
# 創建Session
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 創建一個函數來獲取數據庫會話
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from models import User
from database import get_db
app = FastAPI()
# 創建用戶
@app.post("/users/")
def create_user(name: str, email: str, db: Session = Depends(get_db)):
user = User(name=name, email=email)
db.add(user)
db.commit()
db.refresh(user)
return user
# 獲取用戶
@app.get("/users/{user_id}")
def get_user(user_id: int, db: Session = Depends(get_db)):
return db.query(User).filter(User.id == user_id).first()
以上是一個簡單的FastAPI與SQLAlchemy ORM結合使用的示例。你可以根據自己的需求進一步擴展和優化。