欢迎访问宙启技术站
智能推送

快速集成数据库和ORM:使用FastAPI构建数据驱动的应用程序

发布时间:2024-01-01 03:10:45

FastAPI是一个快速,现代的Python web框架,它提供了快速集成数据库和ORM的功能。在使用FastAPI构建数据驱动的应用程序时,你可以使用sqlite、MySQL、PostgreSQL等各种数据库,并使用SQLAlchemy作为ORM来操作数据库。

首先,安装所需的库:

pip install fastapi sqlalchemy databases[sqlite]

接下来,创建一个名为main.py的文件并导入所需的库:

from fastapi import FastAPI
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

app = FastAPI()

# 创建数据库引擎
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)

# 创建Session类
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基本类
Base = declarative_base()

# 定义数据模型
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)

# 创建API路由
@app.get("/users/{user_id}")
def get_user(user_id: int):
    # 获取数据库会话
    db = SessionLocal()
    # 查询用户
    user = db.query(User).filter(User.id == user_id).first()
    # 关闭数据库会话
    db.close()
    # 返回用户信息
    return user

@app.post("/users")
def create_user(name: str, email: str):
    # 创建用户
    user = User(name=name, email=email)
    # 获取数据库会话
    db = SessionLocal()
    # 添加用户到数据库
    db.add(user)
    # 提交数据库操作
    db.commit()
    # 刷新数据库
    db.refresh(user)
    # 关闭数据库会话
    db.close()
    # 返回新创建的用户信息
    return user

在上面的例子中,我们首先创建了数据库引擎,然后创建了一个Session类,它将用于打开和关闭数据库会话。接着,我们定义了一个User模型作为数据库表的结构,然后使用Base.metadata.create_all()方法创建了实际的数据库表。

接下来,我们创建了两个路由函数:get_user()和create_user()。在get_user()函数中,我们首先获取数据库会话,然后使用查询过滤条件获取指定user_id的用户数据,并将其返回。在create_user()函数中,我们首先创建一个User实例,然后获取数据库会话,将用户数据添加到数据库中,并提交数据库操作,最后返回新创建的用户数据。

最后,我们可以使用uvicorn运行应用程序:

uvicorn main:app --reload

现在,我们可以使用curl或Postman等工具测试我们的API了。通过发送GET请求到http://localhost:8000/users/1,我们可以获取指定user_id的用户数据。通过发送POST请求到http://localhost:8000/users,我们可以创建一个新的用户。

快速集成数据库和ORM是使用FastAPI构建数据驱动的应用程序中的常见需求。上面的例子演示了如何使用FastAPI和SQLAlchemy实现这一需求,你还可以根据自己的实际需求修改和扩展这些例子。