0

因此,我尝试使用以下代码通过本地机器上的 Python 3.6.2 连接到 Bluemix 上的 MongoDB(Compose for MongoDB 服务):

import json
import urllib.request
import pymongo
import ssl

#uri is string taken from Service Credentials section of MongoDB Bluemix page
uri_string = "mongodb://admin:<password>@server1:port,server2:port/compose?ssl=true&authSource=admin"
client = pymongo.MongoClient(uri_string)
db = client.handle

#reading in json data from api_url
data = urllib.request.urlopen("api_url")
parsed = json.loads(data)
for item in parsed['resultItemList']:
    db.insert_one(item)

目标是将 JSON 数据插入到我的 MongoDB 中,但在运行 for 循环后,我收到以下错误消息:

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/local/lib/python3.6/site-packages/pymongo/collection.py", line 667, in insert_one
    with self._socket_for_writes() as sock_info:
File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py", line 81, in __enter__
    return next(self.gen)
File "/usr/local/lib/python3.6/site-packages/pymongo/mongo_client.py", line 868, in _get_socket
    server = self._get_topology().select_server(selector)
File "/usr/local/lib/python3.6/site-packages/pymongo/topology.py", line 214, in select_server
    address))
File "/usr/local/lib/python3.6/site-packages/pymongo/topology.py", line 189, in select_servers
    self._error_message(selector))

pymongo.errors.ServerSelectionTimeoutError: SSL handshake failed: [SSL: 
    CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748),SSL 
    handshake failed: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify 
    failed (_ssl.c:748) 

我已经在网上广泛搜索并无法弄清楚。我知道我需要以某种方式从 Bluemix 检索 SSL 证书,但不了解在 python 中执行此操作的正确方法以及 MongoClient() 中的某些选项。我已经安装了 certifi python 包:

python3 -m pip install certifi  

这是不成功的,还尝试关闭 SSL 要求

ssl_cert_reqs=ssl.CERT_NONE
4

1 回答 1

0

尝试这个。我的作品。

import os
import pymongo
import ssl

MONGODB_URL = os.environ.get('MONGODB_URL')
client = pymongo.MongoClient(MONGODB_URL,ssl_cert_reqs=ssl.CERT_NONE)
db = client.get_default_database()
print db.collection_names()
于 2018-03-15T04:52:38.353 回答