使用Python 3.6.2连接到IBM Bluemix上的MongoDB
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Python 3.6.2连接到IBM Bluemix上的MongoDB相关的知识,希望对你有一定的参考价值。
因此,我尝试使用以下代码在本地计算机上通过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
答案
试试这个。我的工作。
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()
以上是关于使用Python 3.6.2连接到IBM Bluemix上的MongoDB的主要内容,如果未能解决你的问题,请参考以下文章
连接到 IBM Websphere MQ 时出现 NullPointerException
使用 PHP Cloud Foundry 应用程序连接到 IBM zOS 系统/DB2 表