python - 将 mongoengine.connect 从 django 中的 setting.py 中取出

标签 python django mongodb mongoengine

为了在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/

相关文章:

python - 插值/调整 3D 数组

Django:控制TemporaryUploadedFile生命周期的时间

mongodb - 如何启用 Mongodb Atlas 静态数据加密

python - Pandas 分类错误 : "Cannot setitem on a Categorical with a new category, set the categories first"

python - 使用边缘检测和 scikit-image 在 Python 中去除背景/屏蔽

python - 使用python查找搜索字符串位于pdf文档中的哪个页面

python - Safari 浏览器中的下拉菜单不显示下拉元素

javascript - 当我的导航栏折叠时如何使按钮起作用?

node.js - 查找并更新数组中列出的许多文档

node.js - 使用 docker-compose 将 NodeJS-App 连接到 MongoDB