要在FastAPI中实现数据库集成,可以使用第三方库如SQLAlchemy或者ORM(对象关系映射)。以下是使用SQLAlchemy的基本步骤:
- 安装SQLAlchemy库:
pip install SQLAlchemy
- 创建一个数据库连接:
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db" engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base()
- 创建一个模型类来定义数据库表结构:
from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) name = Column(String) email = Column(String)
- 创建数据库表:
Base.metadata.create_all(bind=engine)
- 在FastAPI应用中使用数据库:
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{user_id}")
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
return {"id": user.id, "name": user.name, "email": user.email}
通过以上步骤,就能在FastAPI应用中实现数据库集成,实现对数据库的增删改查操作。