如何在 Python 中从 MongoDB 和 PyMongo 捕获操作失败
我一直遇到一个问题,在我通过 pymongo 与 mongohq 的 mongodb 连接空闲一段时间(没有查询)后,它会超时。这很好,但是数据库的连接仅在 Django 应用程序启动时创建。看起来重新连接正常,但需要重新进行身份验证。当连接断开并重新连接并且查询尝试运行时,它会引发 OperationFailure
和以下异常值数据库错误:未经授权的 db [shanereustle] 锁类型:-1
code> 告诉我它正在重新连接,但没有进行身份验证。我已经从 pymongo.errors
导入了 OperationFailure
并一直在尝试使用以下 try... except 但我似乎无法捕获错误并进行身份验证。
try:
db.mongohq.shanereustle.blog.find()
except OperationFailure:
db.authenticate() #this function reauthenticates the existing connection
但由于某种原因,这并没有抓住。如果我不使用此代码,而是在查询之前运行 db.authenticate() ,它将很好地重新进行身份验证,但我不想在每个查询上重新进行身份验证。非常欢迎有关正确方法的其他建议,我很感谢您的帮助。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用 find_one() 而不是 find() 吗?后者不会自动遍历光标。
我刚刚用 --auth 数据库尝试过,它有效:
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: