[Twisted-Python] adbapi and ConnectionLost.

Sébastien HEITZMANN 2le at 2le.net
Tue Jan 13 15:32:45 EST 2009


Hi,

for a couple of week i search how i should handle mysql disconnection on
my twisted web service. When I restart the database without restarting
my service i got some ConnectionLost fired. I have used the cp_reconnect
on the connection pool and it seem to work ( the lost connection is
restarted ) but the current query isn't executed.

So my question is how should I handle this case. Should I intercept the
connectionLost and restart the query ? I have several queries in a
single deffer so this method is not easy and clear.

Any advice whould be welcome.

I join the code of a sample resource.

Thanks

Sébastien HEITZMANN


class StartResource(resource.Resource):
    def __init__(self, dbConnection, mdbConnection, config):
        self.db = dbConnection
        self.mdb = mdbConnection
        resource.Resource.__init__(self)

    def render_POST(self, request):
        try:
            uid = request.args['uid'][0]
            key = request.args['kkey'][0]
            conf = unicode(request.args['conf'][0],'utf8')
            self.db.runInteraction(self._start, uid, key, conf, request)
            return server.NOT_DONE_YET
        except Exception, e:
            print str(e)
            request.setResponseCode(http.INTERNAL_SERVER_ERROR, str(e))
            request.write('ERROR:'+str(e))
            request.finish()

    def _start(self, trans, uid, key, conf, request):
        try:
            if not utils.checkKKEY(uid, key, trans):
                r_status = 'ko'
                r_action = ''
                r_params = 'kkey invalid'
                request.write(json.write([r_status, r_action, r_params]))
                request.finish()
                return None

            query = "UPDATE kserver.b set status=-1 where status=0 and
uid=%s"
            query %= (str(uid))
            trans.execute(query)

            query = u"INSERT INTO `b` (uid, conf)"
            query += " VALUES(%s, '%s');" % ( str(uid), dbutil.safe(conf) )
            trans.execute(query)
            bid = trans._cursor.connection.insert_id()
            #trans.commit()
            r_status = 'ok'
            r_action = ''
            r_params = {'bid':str(bid)}
            request.write(json.write([r_status, r_action, r_params]))
            request.finish()
        except Exception, e:
            print str(e)
            request.setResponseCode(http.INTERNAL_SERVER_ERROR, str(e))
            request.write('ERROR:'+str(e))
            request.finish()






More information about the Twisted-Python mailing list