作为一个美妙的语言,Python 除了 SQLAlchemy 外还有很多ORM库。在这篇文章里,我们将来看看几个流行的可选 ORM 库,以此更好地窥探到Python ORM 境况。通过写一段脚本来读写2个表 ,person 和 address 到一个简单的数据库,我们能更好地理解每个ORM库的优缺点。
SQLObject 是一个介于SQL数据库和Python之间映射对象的Python ORM。得益于其类似于Ruby on Rails的ActiveRecord模式,在编程社区变得越来越流行。首个 SQLObject在2002年十月发布。它遵循LGPL许可。
在 SQLObject 中,数据库概念是通过与 SLQAlchemy 非常类似的的一种方式映射到Python的,表映射成类,行作为实例而字段作为属性。它同时提供一种基于Python对象的查询语言,这使得 SQL 更加抽象, 从而为应用提供了数据库不可知性(译注:应用和数据库分离)。
| 1234567891011121314151617181920212223 | $ pip install sqlobjectDownloading/unpacking sqlobjectDownloading SQLObject–1.5.1.tar.gz (276kB): 276kB downloadedRunning setup.py egg_info for package sqlobject warning: no files found matching \’*.html\’warning: no files found matching \’*.css\’warning: no files found matching \’docs/*.html\’warning: no files found matching \’*.py\’ under directory \’tests\’Requirement already satisfied (use —upgrade to upgrade): FormEncode>=1.1.1 in /Users/xiaonuogantan/python2–workspace/lib/python2.7/site–packages (from sqlobject)Installing collected packages: sqlobjectRunning setup.py install for sqlobjectchanging mode of build/scripts–2.7/sqlobject–admin from 644 to 755changing mode of build/scripts–2.7/sqlobject–convertOldURI from 644 to 755 warning: no files found matching \’*.html\’warning: no files found matching \’*.css\’warning: no files found matching \’docs/*.html\’warning: no files found matching \’*.py\’ under directory \’tests\’changing mode of /Users/xiaonuogantan/python2–workspace/bin/sqlobject–admin to 755changing mode of /Users/xiaonuogantan/python2–workspace/bin/sqlobject–convertOldURI to 755Successfully installed sqlobjectCleaning up... |
| 12345678910111213 | >>> from sqlobject import StringCol, SQLObject, ForeignKey, sqlhub, connectionForURI>>> sqlhub.processConnection = connectionForURI(\’sqlite:/:memory:\’)>>>>>> class Person(SQLObject):... name = StringCol()...>>> class Address(SQLObject):... address = StringCol()... person = ForeignKey(\’Person\’)...>>> Person.createTable()[]>>> Address.createTable() |
上面的代码创建了2个简单的表:person 和 address 。为了创建和插入记录到这2个表,我们简单实例化一个person 实例和 一个 address 实例:
| 1234567 | >>> p = Person(name=\’person\’)>>> a = Address(address=\’address\’, person=p)>>> p >>> a <address> |
为了获得或检索新记录, 我们用神奇的 q 对象关联到 Person 和 Address 类: