views:

92

answers:

1

I have been having a problem where after my mongodb connection to mongohq via pymongo goes idle for awhile (no queries), it will timeout. This is fine, but the connection the database is only created when the Django app is started up. It seems like it is reconnecting fine, but it needs to reauthenticate then. When the connection has died and reconnected, and a query tries to run, it raises an OperationFailure and the following exception value database error: unauthorized for db [shanereustle] lock type: -1 which tells me it is reconnecting, but not authenticating. I have imported OperationFailure from pymongo.errors and have been trying to use the following try...except but I can't seem to catch the error, and authenticate.

try:
    db.mongohq.shanereustle.blog.find()
except OperationFailure:
    db.authenticate() #this function reauthenticates the existing connection

But for some reason this does not catch. If instead of this code, I simply run db.authenticate() before the query, it will reauthenticate just fine and go fine, but I don't want to reauthenticate on every query. Other suggestions on proper ways to do this are very welcome and I appreciate the help.

Thanks!

+2  A: 

Can you try a find_one() instead of find(). The latter doesn't iterate over the cursor automatically.

I just tried this with an --auth database, and it worked:

try:
  connection.test.foo.find_one()
except pymongo.errors.OperationFailure:
  print "caught"
Kyle Banker
Perfect! Now, here is another thing I noticed after implementing this. The very first time a query is ran once the connection does die, it raises AutoReconnect. Every page after that it raises OperationFailure. Is there any way I can do try, except, except? I could check for the AutoReconnect first, and then the OperationFailure? Thanks!
Shane Reustle
Update: You can use multiple exceptions, eg: `except (AutoReconnect, OperationFailure):`
Shane Reustle