在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结合使用的示例。你可以根据自己的需求进一步扩展和优化。