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)

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 programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

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.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles