Tornado使用协程异步访问mysql工具:TorMysql
Posted 饭前码字
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tornado使用协程异步访问mysql工具:TorMysql相关的知识,希望对你有一定的参考价值。
最重要一点:
Tormysql的增删改查都会起一个事务,所以即使是查询,也需要最后显式commit;之前在使用的时候就没注意,导致mysql积压了一堆操作,看起来的现象是各种对mysql的操作都延时了。
import tormysql
import pymysql.cursors
from tornado import gen
pool = tormysql.ConnectionPool(
max_connections=500, # max open connections
idle_seconds=7500, # connection idle timeout time, 0 is not timeout
wait_connection_timeout=600, # wait connection timeout
host="x.x.x.x",
user="xxxx",
passwd="passxxx",
db="test_db",
charset="utf8",
cursorclass=pymysql.cursors.DictCursor # 获取的是字典形式, 没有这句获取的是元组
)
class Mysql:
def __init__(self, table):
self.table = table
@gen.coroutine
def fetch(self, select_items, where_items):
table = self.table
with (yield pool.Connection()) as conn:
try:
with conn.cursor() as cursor:
data_count = yield cursor.execute(f"SELECT {select_items} FROM {table} where 1 {where_items}")
resp = cursor.fetchall()
except:
raise gen.Return(None)
else:
yield conn.commit()
raise gen.Return(resp)
@gen.coroutine
def put(self, new_val_map, where_items):
table = self.table
with (yield pool.Connection()) as conn:
try:
with conn.cursor() as cursor:
data_count = yield cursor.execute(f"UPDATE {table} SET {new_val_map} where 1 {where_items}")
except:
yield conn.rollback()
raise gen.Return(False)
else:
yield conn.commit()
raise gen.Return(True)
@gen.coroutine
def post(self, fileds, new_val):
table = self.table
with (yield pool.Connection()) as conn:
try:
with conn.cursor() as cursor:
data_count = yield cursor.execute(f"INSERT INTO {table} {fileds} VALUES {new_val}")
new_id = cursor.lastrowid
except:
yield conn.rollback()
raise gen.Return(False)
else:
yield conn.commit()
raise gen.Return(True)
以上是关于Tornado使用协程异步访问mysql工具:TorMysql的主要内容,如果未能解决你的问题,请参考以下文章