4

I'm build mongodb-cluster with replication and sharding. I'm set x509-based authentication. I'm connect to database (mongos) by mongo as:

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

How do I connect to the cluster using the mongoengine?

I did not find the description of the connection options for the method register_connection:

def register_connection (alias, name = None, host = None, port = None,
                         read_preference = READ_PREFERENCE,
                         username = None, password = None, authentication_source = None,
                         ** Kwargs):

For example PyMongo provides the necessary options http://api.mongodb.com/python/current/examples/authentication.html#mongodb-x509 but I need use mongoengine in existing code.

4 Answers 4

5

I looked dokstring "register_connection" and I found:

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

And I use this as:

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)
1

When using mongoengine connecting to MongoDB Atlas cluster you can use the following simplified function:

# 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

Where the database variable is a string with the name of the database.

1

MongoEngine is base on pymongo. A mongo_url like 'mongodb://user:passwd@ip:port,ip:port/db' work well in MongoEngine and Pymongo.

The code is like this:

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()

For more information: http://docs.mongoengine.org/apireference.html

0

For those who use flask_mongoengine here is the workable solution for an ssl certificate:

# 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.