SQLalchemy 内部结构和设计模式

SQLalchemy internals and design pattern

SQLalchemy 中的设计模式是什么,它是如何工作的?

  1. 我想知道在 db.Model 的子 class 中将每一列定义为 class 变量如何提供创建 table 的必要信息。 db.create_all如何获得这些数据?

  2. 我们通常不会为table显式定义init,但是我们可以使用初始化器。这是怎么做到的?

  3. 为什么采用这个设计?是不是因为class个变量是在解释器到达定义的时候启动的,而实例可以有很多?

  4. 只是为了了解内部结构,假设我们用字典替换 SQL 后端。什么是模拟 SQLalchemy wrt table 定义和 create_all 的最少代码?

我想说您想看看 "The Architecture of Open Source Applications" 中的 SQLAlchemy 章节,尤其是“经典与声明式”部分。

The Declarative extension uses a Python metaclass, which is a handy way to run a series of operations each time a new class is first declared, to generate a new Table object from what's been declared, and to pass it to the mapper function along with the class. The mapper function then does its job in exactly the same way, patching its own attributes onto the class, in this case towards the id attribute, and replacing what was there previously.

我看到这被称为声明性元class 编程。如果您正在寻找一个更温和的示例,那么 Marty Alchin 的“Pro python”有一个更简单的示例,说明此模式将 csv 文件中的列映射到 class、someone has helpfully put just the code up on github尽管这本书对正在发生的事情有更全面的解释。

我将从一篇关于 python 元编程的旧 IBM 文章中添加这条评论。

Metaclasses are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with certainty that they need them, and don't need an explanation about why). -- Python Guru Tim Peters