Search code examples
azureazure-cosmosdbpymongo

How can i connect to Comos DB Emulator with Pymongo?


I'm facing to this problem : i can't connect to a Cosmos Db Emulator with Pymongo. I have the following issue :

Can't connect:localhost:10255: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:997), Timeout: 30s, Topology Description: <TopologyDescription id: 64197ab899525d2c6d0890ff, topology_type: Unknown, servers: [<ServerDescription ('localhost', 10255) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:10255: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:997)')>]>

I followed the Microsoft documentation to start the lastest version the emulator using this command line :

PS C:\Program Files\Azure Cosmos DB Emulator> .\Microsoft.Azure.Cosmos.Emulator.exe /EnableMongoDbEndpoint=3.6

This is the code inspired from Azure Cosmos Emulator 's github to connect to the emulator :

# ------------------------------------------------------------------------------
#  Prerequisites:
#
# 1. An Azure Cosmos DB API for MongoDB Account.
# 2. PyMongo installed.
# 3. python-dotenv installed (to load environment variables from a .env file).
# ------------------------------------------------------------------------------
# Code samples are used in documentation, keep synchronized with documentation.
# ------------------------------------------------------------------------------

# <package_dependencies>
import os
import sys

import pymongo

# </package_dependencies>

def main():
    """Connect to the API for MongoDB"""

    try:
        # <client_credentials>
        client = pymongo.MongoClient("mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/admin?ssl=true")

        for prop, value in vars(client.options).items():
            print("Property: {}: Value: {} ".format(prop, value))
        # </client_credentials>
        try:
            client.server_info()  # validate connection string
        except (
            pymongo.errors.OperationFailure,
            pymongo.errors.ConnectionFailure,
            pymongo.errors.ExecutionTimeout,
        ) as err:
            sys.exit("Can't connect:" + str(err))
    except Exception as err:
        sys.exit("Error:" + str(err))

    print("Connected to MongoDB")

    # <client_disconnect>
    client.close()
    # </client_disconnect>


if __name__ == "__main__":
    main()

I have tried differents start commands to run the emulator like /NoFirewall, /AllowNetworkAccess /KeyFile=cosmosdbauthkey and many others because it seems that the emulator is inaccessible.

Note that the emulator and the test code are running on the same computer.


Solution

  • I would think you need to ignore certificate verification errors:

    client = pymongo.MongoClient(xxx,
        tls=True,
        tlsAllowInvalidCertificates=True)