原始:我最近开始从一些旧代码中获取MySQL操作错误,似乎无法追溯到问题所在。因为它以前是工作的,我想可能是一个软件更新,打破了一些东西。我正在使用Python2.7和django runfcgi和nginx。这是我的原始代码:
视图.pyDBNAME = "test"
DBIP = "localhost"
DBUSER = "django"
DBPASS = "password"
db = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
cursor = db.cursor()
def list(request):
statement = "SELECT item from table where selected = 1"
cursor.execute(statement)
results = cursor.fetchall()
我试过以下方法,但仍然不起作用:
视图.pyclass DB:
conn = None
DBNAME = "test"
DBIP = "localhost"
DBUSER = "django"
DBPASS = "password"
def connect(self):
self.conn = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
def cursor(self):
try:
return self.conn.cursor()
except (AttributeError, MySQLdb.OperationalError):
self.connect()
return self.conn.cursor()
db = DB()
cursor = db.cursor()
def list(request):
cursor = db.cursor()
statement = "SELECT item from table where selected = 1"
cursor.execute(statement)
results = cursor.fetchall()
目前,我唯一的解决方法是在使用mysql的每个函数中执行MySQLdb.connect()。我还注意到,当使用django的manage.py runserver时,我不会有这个问题,而nginx会抛出这些错误。我怀疑我正在超时连接,因为list()正在启动服务器后的几秒钟内被调用。我正在使用的软件是否有任何可能导致此问题的更新/是否有任何解决方案?
编辑:我意识到我最近写了一个中间件来对一个函数进行守护,这就是问题的原因。但是,我不明白为什么。这是中间件的代码def process_request_handler(sender, **kwargs):
t = threading.Thread(target=dispatch.execute,
args=[kwargs['nodes'],kwargs['callback']],
kwargs={})
t.setDaemon(True)
t.start()
return
process_request.connect(process_request_handler)