如何使用 mongoengine 连接到 mongodb-cluster

How to connect to the mongodb-cluster using mongoengine

我正在构建具有复制和分片功能的 mongodb-cluster。我设置了基于 x509 的身份验证。 我通过 mongo 连接到数据库 (mongos) 作为:

mongo admin --ssl --sslCAFile mongoCA.pem \
--sslPEMKeyFile client.pem -u user -p password --host my.host.com --port 27017

如何使用 mongo引擎连接到集群?

我没有找到方法 register_connection:

的连接选项的描述
def register_connection (alias, name = None, host = None, port = None,
                         read_preference = READ_PREFERENCE,
                         username = None, password = None, authentication_source = None,
                         ** Kwargs):

例如 PyMongo 提供了必要的选项 http://api.mongodb.com/python/current/examples/authentication.html#mongodb-x509 但我需要在现有代码中使用 mongo 引擎。

我查看了 dokstring "register_connection" 并发现:

:param kwargs: allow ad-hoc parameters to be passed into the pymongo driver

我将其用作:

import os
import ssl
from mongoengine import DEFAULT_CONNECTION_NAME, register_connection
from pymongo import ReadPreference

db_host = os.getenv('DB_HOST', 'localhost')
db_port = int(os.getenv('DB_PORT', '27017'))
db_name = os.getenv('DB_DATABASE', 'mydatabase')

ssl_certfile = os.getenv('SSL_SERTFILE', 'client.pem')
ssl_cert_reqs = ssl.CERT_REQUIRED
ssl_ca_certs = os.getenv('SSL_CA_CERTS', 'mongoCA.pem')

db_user = os.getenv('DB_USER', 'myUser')
db_pass = os.getenv('DB_PASS', '')

ssl_config = {
    'ssl': True,
    'ssl_certfile': ssl_certfile,
    'ssl_cert_reqs': ssl_cert_reqs,
    'ssl_ca_certs': ssl_ca_certs
}

register_connection(alias=DEFAULT_CONNECTION_NAME,
                    name=db_name,
                    host=db_host,
                    port=db_port,
                    username=db_user,
                    password=db_pass,
                    read_preference=ReadPreference.NEAREST,
                    authentication_source=db_name,
                    **ssl_config)

MongoEngine 基于 pymongo。像 'mongodb://user:passwd@ip:port,ip:port/db' 这样的 mongo_url 在 MongoEngine 和 Pymongo 中运行良好。

代码是这样的:

from mongoengine import connect, Document, StringField

connect('mpc', host='mongodb://mpc:mpc@mongo-1:28010,mongo-2:28010,mongo-3:28010/mpc')

class User(Document):
    title = StringField(required=True, max_length=200)

print User.objects.count()

更多信息:http://docs.mongoengine.org/apireference.html

当使用 mongoengine 连接到 MongoDB Atlas 集群时,您可以使用以下简化函数:

# Connect to, return database
def db_connect(database):
    db_uri = "mongodb+srv://<username>:<password>@<cluster>.net/?retryWrites=true&w=majority"
    db = connect(database, host=db_uri)
    return db

其中数据库变量是带有数据库名称的字符串。

对于那些使用 flask_mongoengine 的人来说,这里是 ssl 证书的可行解决方案:

# config.py
import ssl


class Config(object):
    # some other settings
    # ...
    # db settings
    MONGODB_SETTINGS = {
        'MONGODB_HOST': 'mongodb://username:password@host:port/db_name?replicaSet=rs_name&authSource=db_name',
        'MONGODB_SSL': True,
        'MONGODB_SSL_CERT_REQS': ssl.CERT_REQUIRED,
        'MONGODB_SSL_CA_CERTS': '/path/to/ca/certificate.crt',
    }


# app.py
from flask import Flask
from flask_mongoengine import MongoEngine

from config import Config

app = Flask(__name__)
app.config.from_object(Config)
db = MongoEngine()
db.init_app(app)