我们使用 Django 来运行模型模拟。该代码作为 cronscript 运行(不通过 wsgi)并注册模拟是否成功运行。 在模型模拟开始时,会创建一个状态对象,其状态为 RUNNING。在模型模拟结束时,此状态对象将更新为 SUCCESS 或 FAILED。 (伪)代码如下所示:
def mainRoutine():
myStatusObject = createStatusObject()
try:
runModelSimulation() # this runs the modelsimulation
except:
updateStatus(myStatusObject,'FAILED')
updateStatus(myStatusObject,'SUCCESS')
def createStatusObject():
myStatusObject = models.StatusObject()
myStatusObject.task = 'somename'
myStatusObject.status = 'RUNNING'
myStatusObject.save()
return myStatusObject
def updateStatus(myStatusObject, newstatus):
myStatusObject.status = newstatus
myStatusObject.save()
当模型模拟需要很长时间(可能是几小时到几天的模拟)时,问题就开始了。然后,MySQL 数据库出现连接错误,并显示错误“MySQL 服务器已消失”。我从其他帖子中了解到,这与数据库剩余的某些连接有关(可以通过摆弄 MySQL 的服务器端配置来解决)。
目前我找到了一个解决方法,通过传递 statusobject 的 ID,而不是 statusobject 实例。然后,在 updateStatus 子例程中,我在更新之前使用 get(ID=thisID) 检索正确的 statusObject 实例。这不会产生超时。
def updateStatus(myStatusObjectID, newstatus):
myStatusObject = StatusObject.objects.get(id=myStatusObjectID)
myStatusObject.status = newstatus
myStatusObject.save()
问题解决了吗?!然而,我们还有其他类似于 statusobject 的对象,并且很可能会遇到类似的问题。所以我想了解为什么这个连接保持开放状态。传递 StatusObject 实例和结合 .get() 传递 StatusObject ID 之间有什么区别?在什么时候建立连接,如何防止此连接保持打开状态?我们可以告诉 django 在 .save() 之后关闭连接,并在实例的下一次更新时重新打开它吗? 另外,因为传递 StatusObject 实例比根据其属性搜索它并重新打开它更容易。
最佳答案
在模型模拟之前关闭与 MySQL 的连接。 Django 将在调用 myStatusObject.save()
时自动重新连接到 sql server。
from django.db import connection
def mainRoutine():
myStatusObject = createStatusObject()
connection.close()
try:
runModelSimulation() # this runs the modelsimulation
except:
updateStatus(myStatusObject,'FAILED')
updateStatus(myStatusObject,'SUCCESS')
关于python - “MySQL 服务器已经消失”,进程持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27942064/