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.
我一直遇到一个问题,在我的mongodb通过pymongo连接到mongohq后空闲了一段时间(没有查询),它会超时。这很好,但只有在启动Django应用程序时才会创建数据库的连接。好像它重新连接正常,但它需要重新认证。当连接已经死亡并重新连接,并且查询尝试运行时,它会引发OperationFailure和以下异常值数据库错误:db [shanereustle]锁定类型未授权:-1告诉我它正在重新连接,但未进行身份验证。我从pymongo.errors导入了OperationFailure并且一直尝试使用以下尝试...除了但我似乎无法捕获错误,并进行身份验证。
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.
但由于某种原因,这并没有抓住。如果不是这个代码,我只是在查询之前运行db.authenticate(),它将重新进行验证并且正常,但我不想在每个查询上重新验证。关于正确方法的其他建议非常受欢迎,我感谢您的帮助。
Thanks!
1 个解决方案
#1
6
Can you try a find_one() instead of find(). The latter doesn't iterate over the cursor automatically.
你可以试试find_one()而不是find()。后者不会自动迭代光标。
I just tried this with an --auth database, and it worked:
我只是尝试使用--auth数据库,它工作:
try:
connection.test.foo.find_one()
except pymongo.errors.OperationFailure:
print "caught"
#1
6
Can you try a find_one() instead of find(). The latter doesn't iterate over the cursor automatically.
你可以试试find_one()而不是find()。后者不会自动迭代光标。
I just tried this with an --auth database, and it worked:
我只是尝试使用--auth数据库,它工作:
try:
connection.test.foo.find_one()
except pymongo.errors.OperationFailure:
print "caught"