1.安装ultramysql
pip install git+https://github.com/esnme/ultramysql.git
2.安装ultramysql的MySQLdb包装库(patch掉ultramysql,来兼容MySQLdb特征)
包装以后,就不需要安装MySQLdb了, 用到MySQLdb的地方相当于使用ultramysql,从而可以在gevent使用ponyorm了
pip install git+https://github.com/hongqn/umysqldb.git
3.安装ponyorm
pip install git+https://github.com/ponyorm/pony.git
测试
# -*- coding: utf-8 -*- from gevent import monkey; monkey.patch_all() from pony import orm import gevent DB = dict(host="127.0.0.1", user="root", passwd="123456", db="test", ) db = orm.Database("mysql", **DB) class Person(db.Entity): _table_ = "person" name = orm.Required(unicode) age = orm.Required(int) motto = orm.Optional(unicode) cars = orm.Set("Car") class Car(db.Entity): _table_ = "car" owner = orm.Required(Person) model = orm.Required(unicode) # orm.sql_debug(True) db.generate_mapping(create_tables=False) def test_insert1(): print "test_insert1 start.." with orm.db_session: p1 = Person(name="fk", age=24) car1 = Car(owner=p1, model="Lexus") print "test_insert1 end.." def test_insert2(): print "test_insert2 start.." with orm.db_session: p1 = Person(name="gp", age=24) car1 = Car(owner=p1, model="Lexus") print "test_insert2 end.." gevent.spawn(test_insert1) gevent.spawn(test_insert2) print "main coroutine.." gevent.wait() __all__ = ["Person", "Car", "db"]
result:
main coroutine.. test_insert1 start.. test_insert2 start.. test_insert1 end.. test_insert2 end..
根据log顺序可知, ponyorm已经可以在gevent中阻塞就切换协程了