gpt4 book ai didi

python - 如何在 Python 中从 MongoDB 和 PyMongo 捕获 OperationFailure

转载 作者:IT老高 更新时间:2023-10-28 13:27:54 27 4
gpt4 key购买 nike

我一直遇到一个问题,在我通过 pymongo 连接到 mongohq 的 mongodb 连接空闲一段时间(没有查询)后,它会超时。这很好,但数据库连接仅在 Django 应用程序启动时创建。看起来它重新连接正常,但它需要重新验证。当连接断开并重新连接,并且查询尝试运行时,它会引发 OperationFailure 和以下异常值 database error: authorized for db [shanereuSTLe] lock type: -1 告诉我它正在重新连接,但没有进行身份验证。我已从 pymongo.errors 导入 OperationFailure 并一直在尝试使用以下 try...except 但我似乎无法捕捉到错误并进行身份验证。

try:
db.mongohq.shanereustle.blog.find()
except OperationFailure:
db.authenticate() #this function reauthenticates the existing connection

但由于某种原因,这并没有捕捉到。如果我只是在查询之前运行 db.authenticate() 而不是这段代码,它会重新验证并正常运行,但我不想在每个查询上重新验证。非常欢迎其他有关正确方法的建议,感谢您的帮助。

谢谢!

最佳答案

您可以尝试使用 find_one() 代替 find()。后者不会自动遍历光标。

我刚刚用 --auth 数据库尝试了这个,它成功了:

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

关于python - 如何在 Python 中从 MongoDB 和 PyMongo 捕获 OperationFailure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3442267/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com