Python
This section describes how to use the MongoDB client in Python to connect to a cluster instance.
Prerequisites
- To connect an ECS to an instance, the ECS must be able to communicate with the DDS instance. You can run the following command to connect to the IP address and port of the instance server to test the network connectivity.
curl ip:port
If the message It looks like you are trying to access MongoDB over HTTP on the native driver port is displayed, the network connectivity is normal.
- Install Python and third-party installation package pymongo on the ECS. Pymongo 2.8 is recommended.
- If SSL is enabled, you need to download the root certificate and upload it to the ECS.
Connection Code
- Enabling SSLimport sslfrom pymongo import MongoClientconn_urls="mongodb://rwuser:rwuserpassword@ip:port/{mydb}?authSource=admin"connection = MongoClient(conn_urls,connectTimeoutMS=5000,ssl=True, ssl_cert_reqs=ssl.CERT_REQUIRED,ssl_match_hostname=False,ssl_ca_certs=${path to certificate authority file})dbs = connection.database_names()print "connect database success! database names is %s" % dbs
- Disabling SSLimport sslfrom pymongo import MongoClientconn_urls="mongodb://rwuser:rwuserpassword@ip:port/{mydb}?authSource=admin"connection = MongoClient(conn_urls,connectTimeoutMS=5000)dbs = connection.database_names()print "connect database success! database names is %s" % dbs
Note
- The authentication database in the URL must be admin. That means setting authSource to admin.
In SSL mode, you need to manually generate the trustStore file.
- The authentication database must be admin, and then switch to the service database.
Parent topic: Connecting to a Cluster Instance Using Program Code
- Prerequisites
- Connection Code