首先需要下载AWS DocumentDB集群的TLS pem bundle。这个bundle是由证书和私钥文件组成的,用于身份验证和加密通信。
安装Python驱动程序pymongo和ssl模块,并将TLS pem bundle放在一个路径下。
使用pymongo建立连接,并指定使用TLS pem bundle作为CA证书和客户端证书。
示例代码:
import pymongo
import ssl
# 导入TLS pem bundle文件
ssl_ctx = ssl.create_default_context(cafile="path/to/rds-combined-ca-bundle.pem")
ssl_ctx.load_cert_chain("path/to/client.pem", "path/to/client.key")
# 建立MongoDB连接
client = pymongo.MongoClient(
"mongodb+srv://-mongodb.net",
ssl=True,
ssl_certfile="path/to/client.pem",
ssl_keyfile="path/to/client.key",
ssl_ca_certs="path/to/rds-combined-ca-bundle.pem",
ssl_context=ssl_ctx
)
# 访问集合
db = client.test
collection = db.my_collection