Home Backend Development Python Tutorial Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍

Python ORM框架SQLAlchemy学习笔记之映射类使用实例和Session会话介绍

Jun 16, 2016 am 08:43 AM
python sqlalchemy mapping

1. 创建映射类的实例(Instance)

前面介绍了如何将数据库实体表映射到Python类上,下面我们可以创建这个类的一个实例(Instance),我们还是以前一篇文章的User类为例,让我们创建User对象:

复制代码 代码如下:

>>> ed_user = User('ed', 'Ed Jones', 'edspassword')
>>> ed_user.name
'ed'
>>> ed_user.password
'edspassword'
>>> str(ed_user.id)
'None'
和普通的Python类一样实例化,大家可能会问为什么ed_user.id会是None值,首先id这个属性没有通过__init__()构造方法初始化,所以默认会因为先前定义的ORM的id列(Column)而产生一个None值,在默认情况下,ORM会为所有被映射的表列创建类属性,这些属性是通过Python语言中描述符(Descriptors)机制来实现的。所以这些属性的使用会包含一些额外的行为,包括跟踪修改,或者当需要时自动从数据库加载新的数据,也就是说我们在使用这些属性时,包括修改或者读取,都会触发ORM内部的一系列动作。


等等,你还没有说明白为什么id这个属性会为None值呢。呵呵,其实我们现在并没有将数据插入数据库,一般主键这个属性会在插入数据库时自动产生一个不重复的值以保证唯一性。由于我们没有对对象实行持久化(Persist) (所谓的持久化就是把对象数据按照映射关系存储入数据库里) 所以这里id值为None。别着急,稍后当我们介绍将数据持久化后你就可以看到一个新的自动产生的id了。

接下来小偷懒一下,介绍一个偷懒的技巧:-)

假如我们不定义映射类的构造方法__init__()会带来什么不良影响吗?完全不会,SQLAlchemy为我们考虑到这点,假如我们偷懒将先前的User类定义成这样:

复制代码 代码如下:

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
由于User继承自Base (Base定义见上一篇文章),所以受到Declarative系统的管理,Declarative系统发现这个类缺少构造方法,于是很友善的给我们补上了一个构造方法,当然其提供的构造方法则不能像我们自己定义的构造方法那样使用基于位置的参数访问,建议使用基于键的参数访问方式,包括我们所有用Column定义映射的列,比如如下方式:
复制代码 代码如下:

u1 = User(name='ed', fullname='Ed Jones', password='foobar')
id也可以传入,通常意义上这类主键由系统自动维护,我们无需为其赋值。

2. 创建并使用会话(Session)

到这里可谓是“万事俱备,只欠东风了”,用官方文档的话说“我们现在已经准备好和数据库‘交谈'了” (We're now ready to start talking to the database)。ORM的操作句柄(Handle)被称为会话(Session)。为了使用会话,我们需要先配置它,配置Session的代码语句应该和create_engine()创建引擎的代码语句在一个代码级别上(放在一起就行了)。

比如我们利用create_engine()先建立起引擎名字为engine(关于引擎的建立代码可以参考我第一篇文章),然后利用sessionmaker()工厂函数建立起Session类,同时绑定我们现有的引擎,比如代码如下:

复制代码 代码如下:

>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)
假如我们创建Session的代码与创建引擎的代码不在一个级别上呢,比如先sessionmaker()一个Session类,然后才用create_engine()创建了引擎,那么我们还有机会将Session和引擎绑定到一起吗?当然可以,我们可以利用Session类的configure方法来配置引擎绑定,比如这样的:
复制代码 代码如下:

Session = sessionmaker()
# engine = create_engine(...) 创建引擎
Session.configure(bind=engine)  # 到这里engine应该已经创建
到这里通过sessionmaker()工厂创造出的Session类应该绑定了我们先前创建的Engine了,但是会话还没有真正开始,要开始会话我们需要实例化这个Session类:
复制代码 代码如下:

>>> session = Session()
到这里session就获取了由Engine维护的数据库连接池,并且会维持内存中的映射数据直到提交(commit)更改或者关闭会话对象。

到这里会话的建立就讲解完了,接下来会讲解真正的ORM数据库查询部分,欢迎关注!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles