Search code examples
pythonmongodbdatabase-connectionx509mongoengine

How to connect to the mongodb-cluster using mongoengine


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.


Solution

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