参考:

https://www.jianshu.com/p/0d234e14b5d3

1.Connecting

我们通过 create_engine() 来链接数据库,假设我们我们采用SQLite。

from sqlalchemy import create_engine
engine = create_engine('sqlite:///app.db',echo=True)

[文档片段]: create_engine() 的返回值是 Engine 的一个实例,Engine是database的核心接口,通过方言*来处理使用中的database和DBAPI的细节。

Q:Engine是什么?
片段:把Pool和Dialect链接在一起,以提供数据库的链接和行为的资源。
参照SQLAlchemy架构图,Engine通过Connection Pooling来链接数据库,然后通过Dialect执行SQL语句 Q:方言(dialect)是什么?
Dialect用于和数据API进行交流,根据配置文件的不同调用不同的数据库API
说白了就是执行SQL Q:DBAPI是什么?
DB-API是一个规范,他定义了一系列必须的对象和数据库的存取方式。
理解一下,它就是一个规范。。。
SQLAlchemy架构图:


[文档片段]:第一次执行 Engine.execute() 或者 Engine.connect() 的时候,Engine会对Database创建一个实际的DB-API链接,然后使用数据库发出SQL。

・就是一个链接(connect)和执行(execute)的过程

・文档说不会直接使用Engine,稍后会介绍其他东西,是什么呢?

  ※ 读到后面了,后面介绍了Session。Session关联了Engine,和数据库的对话交由Session来实现。

2.Declare a Mapping

[文档片段]:When using the ORM, the configurational process starts by describing the database tables we’ll be dealing with, and then by defining our own classes which will be mapped to those tables.

当使用ORM时,配置过程从描述数据库表开始,然后定义将映射到这些表的类。这两个任务怎么进行的呢?对,是使用 Declarative ,Declarative允许我们创建一个类去描述真实的数据库表,使它们之间建立联系。

Q:这一段说了啥?
ORM和普通的数据库表不同,但是ORM可以转换成数据库表。
那么怎么转化呢?通过Declarative
1.描述一下数据库表,怎么描述的呢?Emmm,研究中...
2.再定义一个类来映射到这个数据库表

[具体如何操作呢?]:

要使用这种映射关系,我们需要继承一个基类,这个基类就是 sqlalchemy.ext.declarative ,如下我们定义这个基类:

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

之后我们就可以创建映射关系了,当然,我们可以创建多个映射关系,只要继承这个基类就行了。

  ※  这里的映射关系指ORM和真实的数据库表之间的映射

比如我们要创建一个用户表,怎么做呢?直接去看官方文档的例子吧 ~

[需要注意的点]:

1.这个类(比如说用户表类),至少得需要一个__tablename__属性

2.至少需要一个Column,还得有个主键

3.__repr__方法是可选的

[文档片段]:SQLAlchemy never makes any assumptions by itself about the table to which a class refers, including that it has no built-in conventions for names, datatypes, or constraints.   But this doesn’t mean boilerplate is required; instead, you’re encouraged to create your own automated conventions using helper functions and mixin classes, which is described in detail at Mixin and Custom Base Classes.

SQLAlchemy 不会对类引用的表做任何假设*,包括命名、数据格式、或者约束。我们鼓励使用帮助函数和混合类来创建自己的约定*,具体请查看Mixin and Custom Base Classes.

这tm说的啥!

3.Create a Schema

[文档片段]:With our User class constructed via the Declarative system, we have defined information about our table, known as table metadata. The object used by SQLAlchemy to represent this information for a specific table is called the Table object, and here Declarative has made one for us.

通过Declarative system构造了User类,这个类我们定义了关于表的信息,即元数据Metadata。

[文档片段]:The MetaData is a registry which includes the ability to emit a limited set of schema generation commands to the database. As our SQLite database does not actually have a users table present, we can use MetaData to issue CREATE TABLE statements to the database for all tables that don’t yet exist. Below, we call the MetaData.create_all() method, passing in our Engine as a source of database connectivity. We will see that special commands are first emitted to check for the presence of the users table, and following that the actual CREATE TABLE statement

MetaData是什么呢?它能够向Database发出一些有限的命令集合,那么问题来了,他能发出什么命令呢?

文档之后又说了,当我们的SQLite Database没有users表的时候,我们可以用MetaData发出 CREATE TABLE 命令去创建一个users表。

最后举了一个例子:通过调用 MetaData.create_all() 方法,把engine当做参数传进去,就能够执行一个CREATE TABLE的命令。

注意:

1.CREATE TABLE只有表不存在的时候才创建成功

2.在执行 MetaData.create_all() 之后才在硬盘上出现app.db文件,单独执行create_engine()方法是没有创建文件的

4.Create an Instance of the Mapped Class

关于__init__()方法要说一下

1.__init__()方法默认会将参数和数据库的字段相匹配。

比如:

ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')

2.当然你也可以自己重写__init__()方法。

5.Create a Session

[文档片段]:We’re now ready to start talking to the database. The ORM’s “handle” to the database is the Session. When we first set up the application, at the same level as our create_engine() statement, we define a Session class which will serve as a factory for new Session objects

Session是什么呢?直译是会话,它是和数据库通话的桥梁(句柄)。

step1:如何创建Session呢?

・用sessionmaker,在create_engine()同一级别下定义Session类,这个Session类作为一个工厂来生产新的Session对象。

step2:如何连接engine和session呢?

・ Session.configure(bind=engine)

step3:实例化Session

・ session = Session()

[文档片段]:The above Session is associated with our SQLite-enabled Engine, but it hasn’t opened any connections yet. When it’s first used, it retrieves a connection from a pool of connections maintained by the Engine, and holds onto it until we commit all changes and/or close the session object.

Session关联上了Engine,但是他还没有打开任何和Engine的链接。

当第一次使用Session时,它从Engine的连接池里获得一个连接,并且一直持续直到我们执行了commit或者关闭了session对象。

6.Adding and Updating Objects

...

...

...

・Building a Relationship

[文档片段]:The above class introduces the ForeignKey construct, which is a directive applied to Column that indicates that values in this column should be constrained to be values present in the named remote column.

总结了一下:

The above class introduces the ForeignKey construct,
上面的例子中使用了ForeignKey

witch is a directive applied to Column
这个ForeignKey是什么呢?
->它是应用于Column的指令
那么Column是什么呢?
->我理解的是Address类中的一个属性,也就是数据库中的一个字段
这句简单的说就是我定义了一个属性(一个字段)user_id that indicates that values in this column should be constrained to be values present in the named remote column.
上面说了定义好了属性(字段)user_id,那么这个user_id有什么限定呢?
->user属性(字段)的值会受到约束,约束来自于另一个表
就是说我定义的这个user_id是和另外一张表有关系的

啊,本来是想说明relationship的,算了,写都写了。。。

[文档片段]:An additional relationship() directive is placed on the User mapped class under the attribute User.addresses.In both relationship() directives, the parameter relationship.back_populates is assigned to refer to the complementary attribute names; by doing so, each relationship() can make intelligent decision about the same relationship as expressed in reverse; on one side, Address.user refers to a User instance, and on the other side, User.addresses refers to a list of Address instances.

另外一个relationship定义在User表中,两个表都要写上relationship来表明之间的关系。

User表中: addresses = relationship( "Address", order_by=Address.id, back_populates="user")

Address表中: user = relationship("User", back_populates="addresses")

[ 那么问题来了,这个back_populates是什么呢? ]

  ->这一句我没怎么读懂,大概就是back_populates是指向另一个关系表中的属性名,从上面的User表和Address表可以看出。

[ 那么这样做的效果是什么呢? ]

  ->能互相引用。。。在Address表中能引用User表实例,在User表中能引用Address表实例。

官方文档粗读 - Tutorial的更多相关文章

  1. MySQL锁和事务(一):InnoDB锁(MySQL 官方文档粗翻)

    // 写在前面,实际上,数据库加锁的类型和范围受到多种因素的影响,例如数据库隔离等级,SQL语句,是否使用主键.索引等等.可以查看博文: http://www.cnblogs.com/zhaoyl/p ...

  2. Django1.7官方文档中的tutorial——翻译

    写下你的第一个Django应用,第一部分 让我们通过例子来学习. 通过这篇指南,我们将会带你浏览一遍一个基本投票应用的创建. 它由两部分组成: 1一个让人们查看投票和进行投票的公共站点 2一个让你添加 ...

  3. [dpdk] 读官方文档(1)

    前提:已读了这本书<<深入浅出dpdk(朱清河等著)>>. 目标:读官方文档,同时跟着文档进行安装编译等工作. http://dpdk.org/doc/guides/index ...

  4. 【翻译】Django Channels 官方文档 -- Tutorial

    Django Channels 官方文档 https://channels.readthedocs.io/en/latest/index.html 前言: 最近课程设计需要用到 WebSocket,而 ...

  5. 第0001题 : 产生随机数(顺便读random模块官方文档)

    看这个之前我准备先看一下random模块的官方文档... 在整个随机模块中,  最基础的就是random, 它产生一个 [0.0, 1.0)的浮点数. 这个模块下所有的函数实际上是绑定在一个叫做ran ...

  6. 读BeautifulSoup官方文档之与bs有关的对象和属性(1)

    自从10号又是5天没更, 是, 我再一次断更... 原因是朋友在搞python, 老问我问题, 我python也是很久没碰了, 于是为了解决他的问题, 我只能重新开始研究python, 为了快速找回感 ...

  7. 读vue-cli3 官方文档的一些学习记录

    原来一直以为vue@cli3 就是创建模板的工具,读了官方文档才知道原来这么有用,不少配置让我长见识了 Prefetch 懒加载配置 懒加载相信大家都是知道的,使用Import() 语法就可以在需要的 ...

  8. hbase官方文档(转)

    FROM:http://www.just4e.com/hbase.html Apache HBase™ 参考指南  HBase 官方文档中文版 Copyright © 2012 Apache Soft ...

  9. HBase官方文档

    HBase官方文档 目录 序 1. 入门 1.1. 介绍 1.2. 快速开始 2. Apache HBase (TM)配置 2.1. 基础条件 2.2. HBase 运行模式: 独立和分布式 2.3. ...

随机推荐

  1. 【Java 设计】如何优雅避免空指针调用

    空指针引入 为了避免空指针调用,我们经常会看到这样的语句 if (someobject != null) { someobject.doCalc();} 最终,项目中会存在大量判空代码,多么丑陋繁冗! ...

  2. Spring组合注解与元注解

    目录 注解说明 源代码 使用范例 注解说明 元注解:可以注解到别的注解上的注解,所以元注解首先基于条件@Target({ElementType.TYPE}) ,目标使用在类文件上 . 组合注解:连个元 ...

  3. Sqlite 常用操作及使用EF连接Sqlite

    Sqlite是一个很轻,很好用的数据库.兼容性很强,由于是一款本地文件数据库,不需要安装任何数据库服务,只需引入第三方开发包就可以.Sqlite的处理速度比MySql和PostgreSQL更快,性能很 ...

  4. 7、Redis五大数据类型---集合(Set)

    一.集合(Set)简介 Set是string类型的无序集合.集合成员是唯一的,这就意味着集合中不能出现重复的数据. Redis 中 集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1). ...

  5. Python格式处理

    目录 一.CVS表格 二.xml 三.json 四.yml 五.配置文件 六.数据库 一.CVS表格 import csv villains = [     ['Doctor', 'No'],     ...

  6. shell脚本 安全删除MySQL大表

    一.简介 源码地址 日期:2018/4/12 介绍:工具用于安全删除MySQL表,对于一些特定场景可能有用 应用场景:大批删除不走索引但是有主键的场景[可以是单列索引,也可是多列索引] 实现思路:根据 ...

  7. 什么是JMS规范?

    一.简介 JMS是什么:JMS是Java提供的一套技术规范和关于消息中间件的协议 JMS干什么用:通过生产者Producer,消息服务器,以及消费者通力合作,使异构系统能进行集成通信,缓解系统瓶颈,提 ...

  8. Nginx SERVER块配置

    1 Listen 指令 Example Configuration Directives 2 server_name指令 2.1 规则 指令后可以跟多个域名,第一个是主域名 *泛域名:进支持在最前或最 ...

  9. IO多路复用技术总结

    来源:微信公众号「编程学习基地」 IO 多路复用概述 I/O 多路复用技术是为了解决进程或线程阻塞到某个 I/O 系统调用而出现的技术,使进程不阻塞于某个特定的 I/O 系统调用. 在IO多路复用技术 ...

  10. WPF之交互触发器(CallMethodAction)学习

    需求背景: 当我们需要制作画板时,我们的VM需要记录我们的坐标并保存到Path的Data中,用我们普通的Command是无法办到的,这时我们就衍生出来了一个交互触发器CallMethodAction ...