目前Tornado中的torndb模块是不支持python3.x,所以需要修改部分torndb源码即可正常使用
1、开发环境介绍
操作系统:win8(64位),python版本:python3.6(32位),IDE:pycharm
2、安装torndb(这里使用pip进行安装)
3、源码修改
- 修改MySQLdb,torndb是依赖于MySQLdb实现的对MySQL数据库操作,但是python3中不支持MySQLdb,而是使用pymysql,所以需要将源码中使用MySQLdb的地方修改为pymysql。
1)修改导入模块
1
2
3
4
5
6
|
import pymysql.connections
import pymysql.converters
import pymysql.cursors
# import MySQLdb.constants
# import MySQLdb.converters
# import MySQLdb.cursors
|
2)修改连接mysql的方式
1
2
3
4
5
|
def reconnect( self ):
"""Closes the existing database connection and re-opens it."""
self .close()
self ._db = pymysql.connect( * * self ._db_args) # MySQLdb.connect(**self._db_args)
self ._db.autocommit( True )
|
3)修改连接参数,以及遍历字段类型时所使用的列表增加元素(python3使用append进行元素的添加,而不是使用加号)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# if MySQLdb is not None:
if pymysql is not None :
# Fix the access conversions to properly recognize unicode/binary
FIELD_TYPE = pymysql.connections.FIELD_TYPE # MySQLdb.constants.FIELD_TYPE
FLAG = pymysql.constants.FLAG # MySQLdb.constants.FLAG
CONVERSIONS = copy.copy (pymysql.converters.conversions) # (MySQLdb.converters.conversions)
field_types = [FIELD_TYPE.BLOB, FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING]
if 'VARCHAR' in vars (FIELD_TYPE):
field_types.append(FIELD_TYPE.VARCHAR)
for field_type in field_types:
# CONVERSIONS[field_type] = [(FLAG.BINARY, str)] + CONVERSIONS[field_type]
CONVERSIONS[field_type] = [(FLAG.BINARY, str )].append(CONVERSIONS[field_type])
# Alias some common MySQL exceptions
IntegrityError = pymysql.IntegrityError # MySQLdb.IntegrityError
OperationalError = pymysql.OperationalError # MySQLdb.OperationalError
|
- 修改连接超时时间,在torndb初始化方法中设置,需要传递给pymysql
1
2
3
|
def __init__( self , host, database, user = None , password = None ,
max_idle_time = 7 * 3600 , connect_timeout = 10 , # 设置连接超时时间,时间是秒
time_zone = "+0:00" , charset = "utf8" , sql_mode = "TRADITIONAL" ):
|
- 修改查询方法中的迭代方法(将izip改为zip_longest)
1
2
3
4
5
6
7
8
9
|
def query( self , query, * parameters, * * kwparameters):
"""Returns a row list for the given query and parameters."""
cursor = self ._cursor()
try :
self ._execute(cursor, query, parameters, kwparameters)
column_names = [d[ 0 ] for d in cursor.description]
return [Row(itertools.zip_longest(column_names, row)) for row in cursor]
finally :
cursor.close()
|
4、测试使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class IndexHandler(RequestHandler):
def get( self , * args, * * kwargs):
# get返回的是字典对象
ret = self .application.db.get( 'select title from houses where id = 2' )
self .write(ret[ 'title' ])
if __name__ = = '__main__' :
options.parse_command_line()
app = Application([
(r '/' , IndexHandler),
], debug = True )
# 建立数据库连接
app.db = torndb.Connection(
host = '127.0.0.1' ,
database = 'demo' ,
user = 'you_ruser' ,
password = 'your_password'
)
http_server = httpserver.HTTPServer(app)
http_server.listen(options.port)
ioloop.IOLoop.current().start()
|