为了在Python/Django 中使用Mongoengine 连接MongoDB,网络上的大多数博客文章和示例都建议我们应该将这些行添加到settings.py
文件中应用程序:
from mongoengine import connect
connect('project1', host='localhost')
它适用于大多数情况,除了我最近遇到的情况: 当数据库宕机时!
假设如果数据库出现故障,负责 Web 服务器的进程(在我的例子中是 Supervisord
)将停止运行应用程序,因为 connect
throw 。它可能会再尝试几次,但在达到超时后,它将停止尝试。
因此,即使您的应用程序有一些未绑定(bind)到数据库的部分,它们也会崩溃。
一个快速的解决方案是在连接代码中添加一个 try/exception block :
try:
connect('project1', host='localhost')
except Exception as e:
print(e)
但我正在寻找一种更好、更干净的方法来处理这个问题。
最佳答案
不幸的是,这对于 mongoengine
来说是不可能的,除非你像以前一样使用 try-except
解决方案。
您可以尝试使用 MongoClient
连接纯 pymongo
版本 3.0+,并在 mongoengine.connection._connection_settings
字典中手动注册连接(相当hacky但应该工作)。来自 pymongo documentation :
Changed in version 3.0: MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into MongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs.
The MongoClient constructor no longer blocks while connecting to the server or servers, and it no longer raises ConnectionFailure if they are unavailable, nor ConfigurationError if the user’s credentials are wrong. Instead, the constructor returns immediately and launches the connection process on background threads.
关于python - 将 mongoengine.connect 从 django 中的 setting.py 中取出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35405856/