Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch an OperationFailure from MongoDB and PyMongo in Python

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!

like image 432
Shane Reustle Avatar asked Aug 09 '10 16:08

Shane Reustle


1 Answers

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"
like image 70
Kyle Banker Avatar answered Nov 26 '22 18:11

Kyle Banker