如何在 Python 中从 MongoDB 和 PyMongo 捕获操作失败

发布于 2024-09-13 17:44:11 字数 682 浏览 6 评论 0原文

我一直遇到一个问题,在我通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山人契 2024-09-20 17:44:15

您可以尝试使用 find_one() 而不是 find() 吗?后者不会自动遍历光标。

我刚刚用 --auth 数据库尝试过,它有效:

try:
  connection.test.foo.find_one()
except pymongo.errors.OperationFailure:
  print "caught"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文