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. 如何运用TurboDemo创建视频示例

    TurboDemo不仅可以速抓取屏幕截图,而且可高效制作出时尚美观的介绍.演示动画.软件模拟以及使用说明.下面的例子将会告诉使用者们如何分步创建一个视频示例,帮助使用者们快速的上手: 1.开启Turb ...

  2. hadoop-2.6.0-src源码导入Eclipse 转载

    转载地址:http://m.blog.csdn.net/blog/le119126/42009281 一.导入 先修改源码 参考 二.改错里面的第3条 1.cd到 hadoop-2.6.0-src/h ...

  3. oracle 数据库Cmd命令导入导出

    imp 导入数据库:       1.直接导入数据表:   imp username/passwork@orcl file=d:/AA.dmp          eg: imp 用户名/密码@orcl ...

  4. Anroid 数据库的创建

    创建数据库首先要了解SQLiteOpenHelper类 1.构造方法 public SQLiteOpenHelper(Context context,String name, SQLiteDataba ...

  5. smarty模板引擎

    1.    使用smarty 1.1 项目引入 // 3, 连接数据库,提取相关数据 $title = "Smarty模板引擎"; $content = "Smarty模 ...

  6. 关于APP程序员泡沫经济

    这些年,移动互联网非常火,火到掀起学习iOS.安卓以及H5的热潮.有人将这些新技术作为自己的实力补充,增加竞争力:更多的人将它们作为主业,专职做移动开发.但是,即便有移动开发人员不断涌入,对整个行业来 ...

  7. 监狱3D指纹门禁系统解决方案

    由于监狱的行业特殊性,其安全性对社会的安定团结具有重大影响力.因此,采用高新技术来建立监狱的安全屏障,提高监狱安全的规范化.科学化管理水平.用高效的技术防范手段对监狱安全实行事前的主动的防范,保障社会 ...

  8. matlab basic operation command

    Matlab basic operation: >> 5+6 ans = 11 >> 3*4 ans = 12 >> 2^6 ans = 64 >> 1 ...

  9. avalon学习笔记

    背景: 刚刚到一家新的公司,我新接手的项目采用的mvvm框架是avalon,当然我以前没有学过angular,但是用过react,所以对于这类框架应该不算陌生.但毕竟是一个新的框架,所以还是先学起来, ...

  10. hdu-5525 Product(费马小定理)

    题目来源:http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=644&pid=1003 前面用奇偶性约掉2, ...