Skip to content

Commit b27a311

Browse files
committed
Compatible with Python 2.7.x and 3.4.x
1 parent c37f12c commit b27a311

3 files changed

Lines changed: 47 additions & 33 deletions

File tree

hawkular/metrics.py

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
1+
from __future__ import unicode_literals
2+
3+
import codecs
14
import json
2-
import urllib2
3-
import urllib
45
import time
56
import collections
67

8+
try:
9+
# Python 3
10+
from urllib.request import Request, urlopen, build_opener, install_opener, HTTPErrorProcessor
11+
from urllib.error import HTTPError, URLError
12+
from urllib.parse import quote, urlencode
13+
except ImportError:
14+
# Fall back to Python 2's urllib2
15+
from urllib2 import Request, urlopen, URLError, HTTPError, HTTPErrorProcessor, build_opener, install_opener
16+
from urllib import quote, urlencode
17+
718
"""
8-
TODO: Remember to do imports for Python 3 also and check the compatibility..
919
TODO: Search datapoints with tags.. tag datapoints.
1020
TODO: Allow changing instance's tenant?
1121
TODO: Authentication when it's done..
1222
TODO: Remove HawkularMetricsConnectionError and use HawkularMetricsError only?
1323
TODO: HWKMETRICS-110 (fetching a single definition)
24+
TODO: Tag queries, stats queries
1425
"""
1526

1627
class MetricType:
@@ -31,21 +42,21 @@ class Availability:
3142
Up = 'up'
3243
Unknown = 'unknown'
3344

34-
class HawkularMetricsError(urllib2.HTTPError):
45+
class HawkularMetricsError(HTTPError):
3546
pass
3647

37-
class HawkularMetricsConnectionError(urllib2.URLError):
48+
class HawkularMetricsConnectionError(URLError):
3849
pass
3950

40-
class HTTPErrorProcessor(urllib2.HTTPErrorProcessor):
51+
class HawkularHTTPErrorProcessor(HTTPErrorProcessor):
4152
"""
4253
Hawkular-Metrics uses http codes 201, 204
4354
"""
4455
def http_response(self, request, response):
4556

4657
if response.code in [200, 201, 204]:
4758
return response
48-
return urllib2.HTTPErrorProcessor.http_response(self, request, response)
59+
return HTTPErrorProcessor.http_response(self, request, response)
4960

5061
https_response = http_response
5162

@@ -75,15 +86,15 @@ def __init__(self,
7586
self.port = port
7687
self.path = path
7788

78-
opener = urllib2.build_opener(HTTPErrorProcessor())
79-
urllib2.install_opener(opener)
89+
opener = build_opener(HawkularHTTPErrorProcessor())
90+
install_opener(opener)
8091

8192
"""
8293
Internal methods
8394
"""
8495
@staticmethod
8596
def _clean_metric_id(metric_id):
86-
return urllib.quote(metric_id, '')
97+
return quote(metric_id, '')
8798

8899
def _get_base_url(self):
89100
return "http://{0}:{1}/{2}/".format(self.host, str(self.port), self.path)
@@ -110,21 +121,28 @@ def _http(self, url, method, data=None):
110121
res = None
111122

112123
try:
113-
req = urllib2.Request(url=url)
124+
req = Request(url=url)
114125
req.add_header('Content-Type', 'application/json')
115126
req.add_header('Hawkular-Tenant', self.tenant_id)
116127

117128
if not isinstance(data, str):
118129
data = json.dumps(data, indent=2)
119130

131+
# writer = codecs.getencoder('utf-8')
132+
reader = codecs.getreader('utf-8')
133+
120134
if data:
121-
req.add_data(data)
135+
try:
136+
req.add_data(data)
137+
except AttributeError:
138+
req.data = data.encode('utf-8')
122139

123-
req.get_method = lambda: method
124-
res = urllib2.urlopen(req)
140+
req.get_method = lambda: method
141+
res = urlopen(req)
125142
if method == 'GET':
126143
if res.getcode() == 200:
127-
data = json.load(res)
144+
data = json.load(reader(res))
145+
128146
elif res.getcode() == 204:
129147
data = {}
130148

@@ -147,14 +165,14 @@ def _post(self, url, data):
147165
self._http(url, 'POST', data)
148166

149167
def _get(self, url, **url_params):
150-
params = urllib.urlencode(url_params)
168+
params = urlencode(url_params)
151169
if len(params) > 0:
152170
url = '{0}?{1}'.format(url, params)
153171

154172
return self._http(url, 'GET')
155173

156174
def _handle_error(self, e):
157-
if isinstance(e, urllib2.HTTPError):
175+
if isinstance(e, HTTPError):
158176
# Cast to HawkularMetricsError
159177
e.__class__ = HawkularMetricsError
160178
err_json = e.read()
@@ -167,7 +185,7 @@ def _handle_error(self, e):
167185
e.msg = err_json
168186

169187
raise e
170-
elif isinstance(e, urllib2.URLError):
188+
elif isinstance(e, URLError):
171189
# Cast to HawkularMetricsConnectionError
172190
e.__class__ = HawkularMetricsConnectionError
173191
e.msg = "Error, could not send event(s) to the Hawkular Metrics: " + str(e.reason)
@@ -312,7 +330,7 @@ def delete_metric_tags(self, metric_type, metric_id, **deleted_tags):
312330
"""
313331
Delete one or more tags from the metric definition. The tag values must match what's stored on the server.
314332
"""
315-
tags = ','.join("%s:%s" % (key,val) for (key,val) in deleted_tags.iteritems())
333+
tags = ','.join("%s:%s" % (key,val) for (key,val) in deleted_tags.items())
316334
tags_url = self._get_metrics_tags_url(self._get_metrics_single_url(metric_type, metric_id)) + '/{0}'.format(tags)
317335

318336
self._delete(tags_url)
@@ -334,12 +352,6 @@ def create_tenant(self, tenant_id):
334352
"""
335353
item = { 'id': tenant_id }
336354

337-
# if retention_time is not None:
338-
# item['dataRetention'] = retention_time
339-
340-
# if len(tags) > 0:
341-
# item.extend(tags)
342-
343355
tenants_url = self._get_tenants_url()
344356
self._post(tenants_url, json.dumps(item, indent=2))
345357

hawkular/metrics_test.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import unicode_literals
2+
13
import unittest
24
import uuid
35
from metrics import *
@@ -6,7 +8,7 @@ class TestMetricFunctionsBase(unittest.TestCase):
68

79
def setUp(self):
810
self.maxDiff = None
9-
self.test_tenant = unicode(str(uuid.uuid4()))
11+
self.test_tenant = str(uuid.uuid4())
1012
self.client = HawkularMetricsClient(tenant_id=self.test_tenant, port=8080)
1113

1214
class TenantTestCase(TestMetricFunctionsBase):
@@ -16,7 +18,7 @@ class TenantTestCase(TestMetricFunctionsBase):
1618
"""
1719

1820
def test_tenant_creation(self):
19-
tenant = unicode(str(uuid.uuid4()))
21+
tenant = str(uuid.uuid4())
2022
self.client.create_tenant(tenant)
2123
tenants = self.client.query_tenants()
2224

@@ -62,11 +64,11 @@ def test_gauge_creation(self):
6264

6365
# This is what the returned dict should look like
6466
expect = [
65-
{ u'dataRetention': 7, u'type': u'gauge', u'id': u'test.create.gauge.1',
66-
u'tenantId': self.test_tenant },
67-
{u'dataRetention': 90, u'type': u'gauge', u'id': u'test.create.gauge.2', u'tenantId': self.test_tenant},
68-
{u'tags': {u'units': u'bytes', u'env': u'qa'},
69-
u'id': u'test.create.gauge.3', u'dataRetention': 90, u'type': u'gauge', u'tenantId': self.test_tenant}]
67+
{ 'dataRetention': 7, 'type': 'gauge', 'id': 'test.create.gauge.1',
68+
'tenantId': self.test_tenant },
69+
{'dataRetention': 90, 'type': 'gauge', 'id': 'test.create.gauge.2', 'tenantId': self.test_tenant},
70+
{'tags': {'units': 'bytes', 'env': 'qa'},
71+
'id': 'test.create.gauge.3', 'dataRetention': 90, 'type': 'gauge', 'tenantId': self.test_tenant}]
7072

7173
self.assertEqual(m, expect) # Did it?
7274

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from distutils.core import setup
44

55
setup(name='hawkular-client-python',
6-
version='0.3.5',
6+
version='0.3.6',
77
description='Python client to communicate with Hawkular over HTTP',
88
author='Michael Burman',
99
author_email='miburman@redhat.com',

0 commit comments

Comments
 (0)