基于python3.x,使用Tornado中的torndb模块操作数据库

目前Tornado中的torndb模块是不支持python3.x,所以需要修改部分torndb源码即可正常使用

1、开发环境介绍

操作系统:win8(64位),python版本:python3.6(32位),IDE:pycharm

2、安装torndb(这里使用pip进行安装)

1

pip install torndb

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[0for 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值