我正在用 python 3 编写一个脚本,该脚本正在监听隧道并根据收到的消息在 MySQL 中保存和更新数据。
我陷入了奇怪的行为,我使用pymysql模块与MySQL建立了一个简单的连接,一切工作正常,但是过了一段时间这个简单的连接就关闭了。
所以我决定实现 MySQL 的池连接,这就出现了问题。发生的事情没有错误,但问题如下:
我的光标=产量self._pool.execute(query, list(filters.values()))
光标结果=tornado_mysql.pools.Pool对象位于0x0000019DE5D71F98
像这样的堆栈不做任何事情
如果我从光标中删除yield,则传递该行,下一行将引发错误
响应=产量c.fetchall()
属性错误:“Future”对象没有属性“fetchall”
如何修复 MySQL 池连接以使其正常工作?
我尝试过:
我使用很少的模块进行池连接,所有模块都出现相同的问题
恢复了与 pymysql 的简单连接并再次工作
在我的代码下面:
Python脚本文件
import pika
from model import SyncModel
_model = SyncModel(conf, _server_id)
@coroutine
def main():
credentials = pika.PlainCredentials('user', 'password')
try:
cp = pika.ConnectionParameters(
host='127.0.0.1',
port=5671,
credentials=credentials,
ssl=False,
)
connection = pika.BlockingConnection(cp)
channel = connection.channel()
@coroutine
def callback(ch, method, properties, body):
if 'messageType' in properties.headers:
message_type = properties.headers['messageType']
if message_type in allowed_message_types:
result = ptoto_file._reflection.ParseMessage(descriptors[message_type], body)
if result:
result = protobuf_to_dict(result)
if message_type == 'MyMessage':
yield _model.message_event(data=result)
else:
print('Message type not in allowed list = ' + str(message_type))
print('continue listening...')
channel.basic_consume(callback, queue='queue', no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
except Exception as e:
print('Could not connect to host 127.0.0.1 on port 5671')
print(str(e))
if __name__ == '__main__':
main()
同步模型
from tornado_mysql import pools
from tornado.gen import coroutine, Return
from tornado_mysql.cursors import DictCursor
class SyncModel(object):
def __init__(self, conf, server_id):
self.conf = conf
servers = [i for i in conf.mysql.servers]
for s in servers:
if s['server_id'] == server_id:
// s hold all data as, host, user, port, autocommit, charset, db, password
s['cursorclass'] = DictCursor
self._pool = pools.Pool(s, max_idle_connections=1, max_recycle_sec=3)
@coroutine
def message_event(self, data):
table_name = 'table_name'
query = ''
data = data['message']
filters = {
'id': data['id']
}
// here the connection fails as describe above
response = yield self.query_select(table_name, self._pool, filters=filters)
@coroutine
def query_select(self, table_name, _pool, filters=None):
if filters is None:
filters = {}
combined_filters = ['`%s` = %%s' % i for i in filters.keys()]
where = 'WHERE ' + ' AND '.join(combined_filters) if combined_filters else ''
query = """SELECT * FROM `%s` %s""" % (table_name, where)
c = self._pool.execute(query, list(filters.values()))
response = yield c.fetchall()
raise Return({response})
所有代码都只需要简单地连接到数据库,在我开始使用池示例之后就不再工作了。对于此问题的任何帮助,我们将不胜感激。
这是一个独立的脚本。
最佳答案
池连接不起作用,因此切换回 pymysql 并仔细检查连接
我想发布我的有效答案,只有这个解决方案对我有用
连接mysql之前检查连接是否打开,如果没有则重新连接
if not self.mysql.open: self.mysql.ping(reconnect=True)
关于mysql - Python 脚本数据库连接作为池不起作用,但简单连接正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55651574/