This repository was archived by the owner on May 9, 2023. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork9
Patch pymysql to support tornado asynchronous
License
NotificationsYou must be signed in to change notification settings
zhu327/greentor
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
greentor is a fork ofgTornado
greentor通过给pymysql打补丁,使pymysql在Tornado中的运行过程变为异步IO,相比于其它支持Tornado的mysql驱动,greentor有以下不同
- 同步pymysql的写法
- 理论上可以支持各种ORM的调用异步
感谢@snower,参考他的TorMySQL优化了IOStream的读写性能
pip install git+https://github.com/zhu327/greentor.git
# coding: utf-8fromgreentorimportgreengreen.enable_debug()fromgreentorimportmysqlmysql.patch_pymysql()
green.enable_debug()
非必须,开启greenlet调试模式,可以打印greenlet switch过程mysql.patch_pymysql()
给pymysql打异步补丁,异步的pymysql依赖于Tornado,在Tornado的IOLoop start后才能正常使用
涉及到pymysql的调用都需要运行在greenlet中,提供了3种方式实现同步代码转异步
fromgreentorimportgreenfromgreentorimportmysqlmysql.patch_pymysql()importtornado.webclassMainHandler(tornado.web.RequestHandler):@green.greendefget(self):connect=MySQLdb.connect(user='root',passwd='',db='test',host='localhost',port=3306)cursor=connect.cursor()cursor.execute('SELECT * FROM app_blog LIMIT 1')result=cursor.fetchone()cursor.close()connect.close()self.finish(result[2])
通过green.green
装饰器使整个get方法都运行在greenlet中,这样是最方便的使用pymysql的方式
fromgreentorimportgreenfromgreentorimportmysqlmysql.patch_pymysql()importtornado.webimporttornado.gen@green.greendeftest_mysql():connect=MySQLdb.connect(user='root',passwd='',db='test',host='localhost',port=3306)cursor=connect.cursor()cursor.execute('SELECT * FROM app_blog LIMIT 1')result=cursor.fetchone()cursor.close()connect.close()returnresultclassMainHandler(tornado.web.RequestHandler):@tornado.gen.coroutinedefget(self):result=yieldtest_mysql()self.finish(result[2])
通过green.green
装饰器包装的函数会返回Future
对象,可以在Tornado的协程中使用
fromgreentorimportgreenfromgreentorimportmysqlmysql.patch_pymysql()importtornado.webimporttornado.gendeftest_mysql():connect=MySQLdb.connect(user='root',passwd='',db='test',host='localhost',port=3306)cursor=connect.cursor()cursor.execute('SELECT * FROM app_blog LIMIT 1')result=cursor.fetchone()cursor.close()connect.close()returnresultclassMainHandler(tornado.web.RequestHandler):@tornado.gen.coroutinedefget(self):result=yieldgreen.spawn(test_mysql)self.finish(result[2])
green.spawn(callable_obj, *arg, **kwargs)
的调用与green.green
一致
在tests目录下有一个使用纯pymysql调用的实例
demo目录下有一个完整的 Tornado + Django ORM 的环境,具体可以查看demo目录下的README
About
Patch pymysql to support tornado asynchronous
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.