SQLAlchemy

SQLAlchemy is an open source SQL toolkit and ORM for the Python programming language released under the MIT license. It was released initially in February 2006 and written by Michael Bayer. It provides "a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language". It has adopted the data mapper pattern (like Hibernate in Java) rather than the active record pattern (like the one in Ruby on Rails).

SQLAlchemy's unit-of-work principal makes it essential to confine all the database manipulation code to a specific database session that controls the life cycles of every object in that session. Similar to other ORMs, we start by defining subclasses of declarative_base() in order to map tables to Python classes.

 >>> from sqlalchemy import Column, String, Integer, ForeignKey
>>> from sqlalchemy.orm import relationship
>>> from sqlalchemy.ext.declarative import declarative_base
>>>
>>> Base = declarative_base()
>>>
>>>
>>> class Person(Base):
... __tablename__ = 'person'
... id = Column(Integer, primary_key=True)
... name = Column(String)
...
>>>
>>> class Address(Base):
... __tablename__ = 'address'
... id = Column(Integer, primary_key=True)
... address = Column(String)
... person_id = Column(Integer, ForeignKey(Person.id))
... person = relationship(Person)

Before we write any database code, we need to create an database engine for our db session.

 >>> from sqlalchemy import create_engine
>>> engine = create_engine('sqlite:///')

Once we have created a database engine, we can proceed to create a database session and create tables for all the database classes previously defined as Person and Address.

 >>> from sqlalchemy.orm import sessionmaker
>>> session = sessionmaker()
>>> session.configure(bind=engine)
>>> Base.metadata.create_all(engine)

Now the session object becomes our unit-of-work constructor and all the subsequent database manipulation code and objects will be attached to a db session constructed by calling its __init__() method.

 >>> s = session()
>>> p = Person(name='person')
>>> s.add(p)
>>> a = Address(address='address', person=p)
>>> s.add(a)

To get or retrieve the database objects, we call query() and filter() methods from the db session object.

 >>> p = s.query(Person).filter(Person.name == 'person').one()
>>> p >>> print "%r, %r" % (p.id, p.name)
1, 'person'
>>> a = s.query(Address).filter(Address.person == p).one()
>>> print "%r, %r" % (a.id, a.address)
1, 'address'

Notice that so far we haven't committed any changes to the database yet so that the new person and address objects are not actually stored in the database yet. Calling s.commit() will actually commit the changes, i.e., inserting a new person and a new address, into the database.

 >>> s.commit()
>>> s.close()
 

Python’s SQLAlchemy vs Other ORMs[转发 6]SQLAlchemy的更多相关文章

  1. Python’s SQLAlchemy vs Other ORMs[转发 7] 比较结论

    Comparison Between Python ORMs For each Python ORM presented in this article, we are going to list t ...

  2. Python’s SQLAlchemy vs Other ORMs[转发 0]

    原文地址:http://pythoncentral.io/sqlalchemy-vs-orms/ Overview of Python ORMs As a wonderful language, Py ...

  3. Python’s SQLAlchemy vs Other ORMs[转发 3]Django's ORM

    Django's ORM Django is a free and open source web application framework whose ORM is built tightly i ...

  4. Python’s SQLAlchemy vs Other ORMs[转发 2]Storm

    Storm Storm is a Python ORM that maps objects between one or more databases and Python. It allows de ...

  5. Python’s SQLAlchemy vs Other ORMs[转发 1]SQLObject

    SQLObject SQLObject is a Python ORM that maps objects between a SQL database and Python. It is becom ...

  6. Python’s SQLAlchemy vs Other ORMs[转发 4]peewee

    peewee peewee is a small, expressive ORM. Compared to other ORMs, peewee focuses on the principal of ...

  7. Python’s SQLAlchemy vs Other ORMs[转发 5] PonyORM

    PonyORM PonyORM allows you to query the database using Python generators. These generators are trans ...

  8. Python 【第六章】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  9. Python操作Redis、Memcache、RabbitMQ、SQLAlchemy

    Python操作 Redis.Memcache.RabbitMQ.SQLAlchemy redis介绍:redis是一个开源的,先进的KEY-VALUE存储,它通常被称为数据结构服务器,因为键可以包含 ...

随机推荐

  1. ADB简单基础命令

    1.查看设备 adb devices 这个命令是查看当前连接的设备, 连接到计算机的android设备或者模拟器将会列出显示 2.安装软件 adb install adb install :这个命令将 ...

  2. wex5 实战 wex5与js的组件关系与执行顺序(父子与先后)

    初学wex5,先理理让人容易混淆的三个概念: 一 基本概念: 1 wex5组件,顾名思义,在编辑窗口右侧的组件集合里的,都是wex5基于开源自创的组件,并封装了一套自已的方法.目的是为了方便.相关方法 ...

  3. BeanUtils.copyProperties()方法和PropertyUtils.copyProperties()的区别

    首先两者来源于同一个包: import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.Prop ...

  4. IOS OC数据类型

    1.只有浮点型数据除以0.0才能得到+-无穷大的数,而整形或char型数据会得到边界值 2.BOOL的实际类型是signed char,他的底层只占一个字节(只有八位),如果将一个较大的非零整数值赋给 ...

  5. 【转】SVN添加文件时的错误处理:...\conf\svnserve.conf:12: Option expected

    转载地址:http://www.linuxidc.com/Linux/2014-09/106683.htm 安装完SVN服务器,添加完用户权限后,准备将本地的项目add到服务器上时,报"C: ...

  6. java.sql.SQLException: ORA-00972: 标识符过长

    经仔细检查,发现sql语句其中两个字段之间没有逗号!

  7. 传感器介绍之DHT11

    一.DHT11介绍 DHT11 数字温湿度传感器,如图所示,是一款含有已校准数字信号输出的温湿度复合传感器.它应用专用的数字模块采集技术和温湿度传感技术,确保产品具有极高的可靠性与卓越的长期稳定性.传 ...

  8. lua 和 c/c++ 交互 (持续更新)

    参考: http://blog.csdn.net/xiaohuh421/article/details/7476485 http://blog.csdn.net/shun_fzll/article/d ...

  9. java 垃圾回收

    转自:http://www.360doc.com/content/13/0305/10/15643_269388816.shtml

  10. http错误码

    2xx  成功  200  正常:请求已完成.  201  正常:紧接 POST 命令.  202  正常:已接受用于处理,但处理尚未完成.  203  正常:部分信息 - 返回的信息只是一部分.   ...