Shane Reustle
Shane Reustle

Reputation: 8952

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!

Upvotes: 7

Views: 7561

Answers (1)

Kyle Banker
Kyle Banker

Reputation: 4359

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"

Upvotes: 7

Related Questions