基於python3.x,使用Tornado中的torndb模塊操做數據庫

目前Tornado中的torndb模塊是不支持python3.x,因此須要修改部分torndb源碼便可正常使用

一、開發環境介紹python

操做系統:win8(64位),python版本:python3.6(32位),IDE:pycharmmysql

二、安裝torndb(這裏使用pip進行安裝)sql

pip install torndb

三、源碼修改數據庫

  • 修改MySQLdb,torndb是依賴於MySQLdb實現的對MySQL數據庫操做,可是python3中不支持MySQLdb,而是使用pymysql,因此須要將源碼中使用MySQLdb的地方修改成pymysql。

1)修改導入模塊python3.x

import pymysql.connections
import pymysql.converters
import pymysql.cursors
# import MySQLdb.constants
# import MySQLdb.converters
# import MySQLdb.cursors

 2)修改鏈接mysql的方式app

    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進行元素的添加,而不是使用加號)oop

 

# 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
    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)
    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()

 

  

 

四、測試使用測試

  • 數據庫

 

  • 源碼
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()
  • 訪問

  • 通過測試,增刪改查等數據庫操做可以正常使用,就不一一展現了
相關文章
相關標籤/搜索