Skip to content

Commit d480d07

Browse files
Fix bug with newer urllib versions (#330)
1 parent 3c2afdb commit d480d07

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

pydruid/client.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
#
1616
import json
1717
import re
18-
from six.moves import urllib
18+
import ssl
19+
import urllib.error
20+
import urllib.request
1921
from base64 import b64encode
2022

2123
from pydruid.query import QueryBuilder
@@ -549,13 +551,16 @@ class PyDruid(BaseDruidClient):
549551

550552
def __init__(self, url, endpoint, cafile=None, http_headers=None):
551553
super(PyDruid, self).__init__(url, endpoint, http_headers=http_headers)
552-
self.cafile = cafile
554+
self.context = None
555+
if cafile:
556+
self.context = ssl.create_default_context()
557+
self.context.load_verify_locations(cafile=cafile)
553558

554559
def _post(self, query):
555560
try:
556561
headers, querystr, url = self._prepare_url_headers_and_body(query)
557562
req = urllib.request.Request(url, querystr, headers)
558-
res = urllib.request.urlopen(url=req, cafile=self.cafile)
563+
res = urllib.request.urlopen(url=req, context=self.context)
559564
data = res.read().decode("utf-8")
560565
res.close()
561566
except urllib.error.HTTPError as e:

tests/test_client.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,30 @@ def test_client_custom_headers(self):
201201
query = create_blank_query()
202202
headers, _, _ = client._prepare_url_headers_and_body(query)
203203
assert headers["custom-header"] == "test"
204+
205+
@patch("pydruid.client.urllib.request.urlopen")
206+
@patch("pydruid.client.ssl.create_default_context")
207+
def test_client_with_cafile(self, mock_create_default_context, mock_urlopen):
208+
response = Mock()
209+
response.read.return_value = """
210+
[ {
211+
"timestamp" : "2015-12-30T14:14:49.000Z",
212+
"result" : [ {
213+
"dimension" : "aaaa",
214+
"metric" : 100
215+
} ]
216+
} ]
217+
""".encode(
218+
"utf-8"
219+
)
220+
mock_urlopen.return_value = response
221+
222+
client = PyDruid("http://localhost:8083", "druid/v2/", cafile="tests/cert.pem")
223+
224+
mock_create_default_context.assert_called_once()
225+
context = mock_create_default_context.return_value
226+
context.load_verify_locations.assert_called_once_with(cafile="tests/cert.pem")
227+
assert client.context == context
228+
229+
client.topn()
230+
assert mock_urlopen.called_with(context=client.context)

0 commit comments

Comments
 (0)