欢迎,来自IP地址为:216.73.216.147 的朋友


Python 应用程序通常将数据存储在关系型数据库中,如果手动编写 SQL 语句,就还需要负责将查询结果(行)转换为对象、关联相关记录,并防范 SQL 注入攻击。此外,每当数据库模式(schema)发生变更时,都必须手动找出并更新所有受影响的查询语句。

对象关系映射(ORM)工具可以将这些繁琐的工作自动化,它通过将 Python 类映射到数据库表来实现这一目标:类对应数据库表,对象对应表中的行,而类的属性则对应表中的列值。

SQLAlchemy 是一款广泛使用的 Python 数据库操作库,它内置的 ORM 不仅能自动生成 SQL 语句,还允许随时查看这些生成的 SQL。

在本教程中,我们将使用 SQLAlchemy ORM 构建一个小型图书馆数据库,从而学习如何定义模型、添加及查询记录、高效加载关联数据,以及处理事务失败的情况。让我们开始吧!

准备条件

若要跟随本教程进行操作,需要具备以下条件:

  • Python 3.11 或更高版本
  • 熟悉 Python 类和类型提示(type hints)
  • 基本的 SQL 知识:了解表、主键、外键以及连接(joins)
  • 在虚拟环境中安装 SQLAlchemy 2.1 或更高版本(安装步骤将在之后介绍)

SQLAlchemy 是我们代码将要使用的库,而 SQLite 则是代码所交互的数据库。SQLite 通过 Python 内置的”sqlite3″模块运行,因此我们无需额外配置数据库服务器。

安装 SQLAlchemy

首先创建并激活虚拟环境:

# python -m venv .venv
# source .venv/bin/activate

如果在 Windows 系统上,则使用”.venv\Scripts\activate”来激活虚拟环境。

随后安装 SQLAlchemy:

# pip install "sqlalchemy>=2.1"

本教程中的代码已在 SQLAlchemy 2.1.9 版本下经过测试。现在创建一个名为”main.py”的文件,并随着教程的进行,将各段 Python 代码片段依次添加到该文件中。

定义自己的类

每个模块都继承自一个共享的基类。首先,创建一个基类:

from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

class Base(DeclarativeBase):
pass

这里,Base 类会记录下我们通过其子类所声明的每一张数据表。

创建作者类

添加一个 Author 类:

class Author(Base):
    __tablename__ = "authors"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    email: Mapped[str] = mapped_column(unique=True)

    books: Mapped[list["Book"]] = relationship(
        back_populates="author", cascade="all, delete-orphan"
    )

让我们来解析一下这个定义:

  • __tablename__ 用于设置表名
  • Mapped[…] 用于声明每个属性的 Python 类型
  • mapped_column() 用于添加数据库层面的详细信息,例如主键、长度或唯一约束
  • relationship() 用于将作者与一系列书籍关联起来,其中的 cascade 选项确保在保存或删除作者时,其关联的书籍也会随之被保存或删除

创建书籍类

每个书籍都会包含一个对应的作者:

class Book(Base):
    __tablename__ = "books"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str] = mapped_column(String(200))
    year: Mapped[int]
    rating: Mapped[float | None]
    author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))

    author: Mapped["Author"] = relationship(back_populates="books")

ForeignKey(“authors.id”) 将两张表关联起来。back_populates 参数则确保了 Python 中该关联关系两侧的数据保持同步。

类型注解还决定了字段是否允许为空:”year”是必填列,而”float | None”则允许”rating”字段为空。

连接到数据库

数据库引擎负责管理与数据库的连接,创建一个引擎,然后创建数据表:

from sqlalchemy import create_engine

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
print(list(Base.metadata.tables))

输出为:

['authors', 'books']

使用”sqlite://”作为 URL 会创建一个内存数据库,因此每次运行程序时,数据都会重置。若要将数据持久化存储在磁盘上,可以使用”sqlite:///library.db”,请会创建对应的数据库文件。

“create_all()”仅会创建尚不存在的表,而不会改动已有的表。因此,当数据库架构(schema)发生变更时,就需要使用 Alembic 等迁移工具进行管理。

添加数据库记录

我们需要通过”会话”(session)与数据库进行交互。可以将其想象成一个购物车:我们往里放入对象,而”commit()”操作就相当于结账。

from sqlalchemy.orm import Session
daehub = Author(
    name="daehub net",
    email="daehub@daehub.com",
    books=[
        Book(title="A Wizard of Internet", year=1968, rating=4.6),
        Book(title="The Dispossessed", year=1974, rating=4.8),
    ],
)

此时,daehub 只是一个存在于内存中的普通 Python 对象。再创建一个新的作者:

wizcenter = Author(
    name="wizcenter",
    email="wizcenter@daehub.com",
    books=[Book(title="Kindred", year=1979)],
)

使用如下代码保存两个作者要数据库:

with Session(engine) as session:
    session.add_all([daehub, wizcenter])
    session.commit()
    print(daehub.id, wizcenter.id)

输出为:

1 2

我们只添加了作者,而 SQLAlchemy 也一并保存了他们所著的书籍。它还自动为我们填好了每个”author_id”。

使用 “with” 代码块会在操作完成后关闭会话;即使发生错误,它也会确保会话被关闭。

查询数据

若要读取数据,可以使用 select() 构建一条语句,并通过会话(session)执行它。

例如获取 1970 年之后出版的书籍,并按出版时间从早到晚排序:

from sqlalchemy import select
stmt = select(Book).where(Book.year > 1970).order_by(Book.year)
with Session(engine) as session:
    for book in session.scalars(stmt):
        print(book.title, book.year)

输出为:

The Dispossessed 1974
Kindred 1979

“scalars()” 会返回可直接操作的 “Book” 对象。如果想了解对应的 SQL语句,可以将该语句打印出来:

print(stmt)

输出为:

SELECT books.id, books.title, books.year, books.rating, books.author_id 
FROM books 
WHERE books.year > :year_1 ORDER BY books.year

“:year_1″占位符表明,该值与 SQL 文本是分开传输的,这能保护查询免受 SQL 注入攻击。

获取单条记录

若要根据主键进行查询,则可以使用”get()”。对于其他最多只会匹配到一行记录的条件,使用”scalar_one_or_none()”:

with Session(engine) as session:
    first_book = session.get(Book, 1)
    print(first_book.title)
    stmt = select(Author).where(Author.email == "nobody@example.com")
    print(session.execute(stmt).scalar_one_or_none())

输出为:

A Wizard of Internet
None

连接并汇总数据表

假设我们想要统计每位作者的书籍数量。需要连接数据表并对行进行分组:

from sqlalchemy import func

stmt = (
    select(Author.name, func.count(Book.id))
    .join(Author.books)
    .group_by(Author.id)
    .order_by(Author.name)
)

“join(Author.books)”会利用关联关系来确定连接条件。由于选择的是特定列,因此需调用”execute()”来获取返回的行数据:

with Session(engine) as session:
    for name, total in session.execute(stmt):
        print(f"{name}: {total}")

输出为:

daehub net: 2
wizcenter: 1

高效加载关联数据

默认情况下,SQLAlchemy 会在首次访问关联关系时将其加载。这被称为延迟加载(lazy loading)。

若要查看其开销,可以添加一个查询计数器:

from sqlalchemy import event

queries = []

@event.listens_for(engine, "before_cursor_execute")
def track_query(conn, cursor, statement, *args):
    queries.append(statement)

例如假设需要遍历作者并访问他们的书籍:

with Session(engine) as session:
    for author in session.scalars(select(Author)):
        print(author.name, len(author.books))

print("Queries:", len(queries))

输出为:

daehub net 2
wizcenter 1
Queries: 3

首先用一次查询获取了所有作者,然后每位作者又各自触发了另一次查询。如果有 500 位作者,总共就会发送 501 次查询。这就是所谓的”N+1 查询问题”。

解决方法是:使用”selectinload()”在初始查询时就一并获取相关的书籍数据。

from sqlalchemy.orm import selectinload

queries.clear()
stmt = select(Author).options(selectinload(Author.books))

with Session(engine) as session:
    for author in session.scalars(stmt):
        print(author.name, len(author.books))

print("Queries:", len(queries))

输出为:

daehub net 2
wizcenter 1
Queries: 2

第二个查询会一次性加载所有作者对应的书籍。在处理集合(collections)时,我们通常会优先选择”selectinload()”。而对于像”Book.author”这种多对一(many-to-one)的关联,使用”joinedload()”则更为合适。

更新和删除记录

若要更新某一行,则可以加载该对象并修改其属性:

with Session(engine) as session:
    stmt = select(Book).where(Book.title == "Kindred")
    kindred = session.scalars(stmt).one()

    kindred.rating = 4.7
    session.commit()
    print(kindred.title, kindred.rating)

输出为:

Kindred 4.7

会话会追踪变更,并在提交时发送一条 UPDATE 语句。

若要删除某一行,则将该对象传给 delete():

with Session(engine) as session:
    author = session.get(Author, 2)
    session.delete(author)
    session.commit()

    remaining = session.scalar(select(func.count(Book.id)))
    print("Books left:", remaining)

输出为:

Books left: 2

删除 wizcenter 的同时也删除了对应的书籍,这是因为”Author.books”上配置了级联(cascade)规则。

如果记不清级联的具体含义也没关系。”Author.books”上的 cascade=”all, delete-orphan” 设置告诉 SQLAlchemy:当删除某位作者时,也应一并删除该作者名下的书籍。

处理事务

事务将多项变更归为一组,确保它们要么全部成功,要么全部失败。

示例场景:在添加一个新作者的同时,提供了一个已被占用的电子邮件地址。

duplicate = Author(name="Another Dupli", email="daehub@daehub.com")

with Session(engine) as session:
    session.add(duplicate)
    session.commit()

执行后会报如下错:

解决方案:将最后一个”with”块替换为下方的代码;该代码通过”session.begin()”开启事务,并会捕获其中出现的错误。

from sqlalchemy.exc import IntegrityError

try:
    with Session(engine) as session, session.begin():
        session.add(Author(name="Author. Dupli", email="daehub@daehub.com"))
        session.add(Author(name="Another Dupli", email="duplic@daehub.com"))
except IntegrityError:
    print("That email already exists. Nothing was saved.")

输出为:

That email already exists. Nothing was saved.

“session.begin()”会在代码块执行成功时提交事务,若抛出异常则回滚事务。代码块中的第二位作者数据本身是合法的,但由于发生了回滚,该插入操作也被一并撤销了。

如果自行调用 commit(),且希望在发生故障后继续使用同一个会话,则可以先调用 session.rollback()来实现。

当应用程序需要创建、读取和更新关联对象时,ORM 是一个不错的选择。若涉及大规模批量操作或复杂的报表需求,使用 SQLAlchemy Core 或手写 SQL 则能让我们获得更精细的控制能力。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注