所以我尝试使用以下代码在本地计算机上通过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
答案 0 :(得分: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()