的Python/Django的脚本对MySQL的僵局崩溃
脚本中的和平与错误认为由于死锁:的Python/Django的脚本对MySQL的僵局崩溃
sqlQuery = """INSERT INTO gps_points (gps_track_segment_id, gps_unit_id, date, lat, lng) SELECT MAX(gps_track_segments.id) AS gps_track_segment_id, %(gps_unit_id)s AS gps_unit_id, %(date)s AS date, %(lat)s AS lat, %(lng)s AS lng FROM gps_track_segments INNER JOIN gps_tracks ON gps_track_segments.gps_track_id = gps_tracks.id WHERE gps_tracks.hash = %(track)s"""
from django.db import connection, transaction
cursor = connection.cursor()
success = cursor.execute(sqlQuery, point)
transaction.commit_unless_managed()
错误日志显示:
2012-08-28 12:37:58,051 - django.db.backends - DEBUG - (0.018) INSERT INTO gps_points (gps_track_segment_id, gps_unit_id, date, lat, lng) SELECT MAX(gps_track_segments.id) AS gps_track_segment_id, 121 AS gps_unit_id, '2012-08-28 12:37:56' AS date, 51361100 AS lat, 4983910 AS lng FROM gps_track_segments INNER JOIN gps_tracks ON gps_track_segments.gps_track_id = gps_tracks.id WHERE gps_tracks.hash = '7f5d950564786e182e175fb5d8e1b937528f85cc1ddabbee0d53859fb603ede3'; args={'gps_unit_id': 121L, 'lat': 51361100, 'date': '2012-08-28 12:37:56', 'course': None, 'track': u'7f5d950564786e182e175fb5d8e1b937528f85cc1ddabbee0d53859fb603ede3', 'speed': '0.0', 'lng': 4983910, 'segment': 5, 'altitude': None, 'accuracy': None}
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
...
...
File "/tcpserver/gpslibs.py", line 75, in saveGpsPoint
success = cursor.execute(sqlQuery, point)
File "/usr/lib/python2.6/site-packages/django/db/backends/util.py", line 40, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 114, in execute
return self.cursor.execute(query, args)
File "/usr/lib64/python2.6/site-packages/MySQLdb/cursors.py", line 173, in execute
self.errorhandler(self, exc, value)
File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
DatabaseError: (1213, 'Deadlock found when trying to get lock; try restarting transaction')
使用MySQL命令SHOW ENGINE INNODB STATUS我看到上面的查询与php网站请求的查询冲突。问题在于,有时候php-request被回滚,有时候是INSERT。最后一种情况导致脚本因死锁错误而停止。 由于涉及更改查询非常困难。我喜欢现在,如果:
我可以以某种方式使Django/Python脚本不会失败的死锁,只是再次尝试? Ofcouse我不真正关心PHP请求失败或获得回滚。从可用性的角度来看,处理这个很容易。我关心后端脚本失败。这需要工作高于一切
回答:
我可以以某种方式使一个Django/Python脚本不会失败的 死锁,只是再次尝试?
您可以捕获该异常升高DatabaseError
,然后执行你的再次执行该交易的逻辑(可能通过收购在桌子上写锁定插入行的第一个前)。
try: success = cursor.execute(sqlQuery, point)
except DatabaseError:
# retry here
你应该最好把它包装在一个你可以再次调用的方法中。
以上是 的Python/Django的脚本对MySQL的僵局崩溃 的全部内容, 来源链接: utcz.com/qa/266645.html