Skip to content
This repository has been archived by the owner on Dec 11, 2023. It is now read-only.

Commit

Permalink
Merge pull request #136 from librato/bugfix/pep8-errors
Browse files Browse the repository at this point in the history
Pep8 fixes
  • Loading branch information
drio authored Aug 25, 2016
2 parents ddc1f6b + 8df776c commit 3f23616
Show file tree
Hide file tree
Showing 30 changed files with 229 additions and 219 deletions.
5 changes: 4 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,7 @@ install:
- "pip install ."
- "pip install six"
- "pip install mock"
script: nosetests tests/
- "pip install pep8"
script:
- nosetests tests/
- pep8 --max-line-length=120
48 changes: 25 additions & 23 deletions librato/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,9 @@
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import re
import six

__version__ = "1.0.7"

# Defaults
HOSTNAME = "metrics-api.librato.com"
BASE_PATH = "/v1/"
DEFAULT_TIMEOUT = 10

import platform
import time
import logging
Expand All @@ -49,6 +42,13 @@
from librato.annotations import Annotation
from librato.spaces import Space, Chart

__version__ = "1.0.7"

# Defaults
HOSTNAME = "metrics-api.librato.com"
BASE_PATH = "/v1/"
DEFAULT_TIMEOUT = 10

log = logging.getLogger("librato")

# Alias HTTPSConnection so the tests can mock it out.
Expand Down Expand Up @@ -83,8 +83,8 @@ class LibratoConnection(object):
[...]
"""

def __init__(self, username, api_key, hostname=HOSTNAME, base_path=BASE_PATH, sanitizer=sanitize_no_op, protocol="https",
tags={}):
def __init__(self, username, api_key, hostname=HOSTNAME, base_path=BASE_PATH, sanitizer=sanitize_no_op,
protocol="https", tags={}):
"""Create a new connection to Librato Metrics.
Doesn't actually connect yet or validate until you make a request.
Expand All @@ -108,7 +108,7 @@ def __init__(self, username, api_key, hostname=HOSTNAME, base_path=BASE_PATH, sa
# these two attributes ared used to control fake server errors when doing
# unit testing.
self.fake_n_errors = 0
self.backoff_logic = lambda backoff: backoff*2
self.backoff_logic = lambda backoff: backoff * 2
self.sanitize = sanitizer
self.timeout = DEFAULT_TIMEOUT
self.tags = dict(tags)
Expand All @@ -133,9 +133,9 @@ def _url_encode_params(self, params={}):
if not isinstance(params, dict):
raise Exception("You must pass in a dictionary!")
params_list = []
for k,v in params.items():
for k, v in params.items():
if isinstance(v, list):
params_list.extend([(k+'[]', x) for x in v])
params_list.extend([(k + '[]', x) for x in v])
else:
params_list.append((k, v))
return urlencode(params_list)
Expand Down Expand Up @@ -179,7 +179,7 @@ def _mexe(self, path, method="GET", query_props=None, p_headers=None):
"""Internal method for executing a command.
If we get server errors we exponentially wait before retrying
"""
conn = self._setup_connection()
conn = self._setup_connection()
headers = self._set_headers(p_headers)
success = False
backoff = 1
Expand Down Expand Up @@ -255,7 +255,7 @@ def submit(self, name, value, type="gauge", **query_props):
metric[k] = v
payload[type + 's'].append(metric)
self._mexe("metrics", method="POST", query_props=payload)

def submit_tagged(self, name, value, **query_props):
payload = {'measurements': []}
if self.tags:
Expand Down Expand Up @@ -391,7 +391,7 @@ def get_annotation_stream(self, name, **query_props):

def get_annotation(self, name, id, **query_props):
"""Get a specific annotation event by ID"""
resp = self._mexe("annotations/%s/%s" % (name,id), method="GET", query_props=query_props)
resp = self._mexe("annotations/%s/%s" % (name, id), method="GET", query_props=query_props)
return Annotation.from_dict(self, resp)

def update_annotation_stream(self, name, **query_props):
Expand All @@ -403,8 +403,8 @@ def update_annotation_stream(self, name, **query_props):
return Annotation.from_dict(self, resp)

def post_annotation(self, name, **query_props):
"""Create an annotation event on :name.
If the annotation stream does not exist, it will be created automatically."""
""" Create an annotation event on :name. """
""" If the annotation stream does not exist, it will be created automatically. """
resp = self._mexe("annotations/%s" % name, method="POST", query_props=query_props)
return resp

Expand Down Expand Up @@ -518,7 +518,6 @@ def delete_space(self, id):
resp = self._mexe("spaces/%s" % id, method="DELETE")
return resp


#
# Charts
#
Expand Down Expand Up @@ -572,16 +571,15 @@ def update_chart(self, chart, space, **query_props):
for k, v in query_props.items():
payload[k] = v
resp = self._mexe("spaces/%s/charts/%s" % (space.id, chart.id),
method="PUT",
query_props=payload)
method="PUT",
query_props=payload)
return resp

def delete_chart(self, chart_id, space_id, **query_props):
"""delete a chart from a space"""
resp = self._mexe("spaces/%s/charts/%s" % (space_id, chart_id), method="DELETE")
return resp


#
# Queue
#
Expand All @@ -600,7 +598,9 @@ def new_queue(self, **kwargs):
def set_timeout(self, timeout):
self.timeout = timeout

def connect(username, api_key, hostname=HOSTNAME, base_path=BASE_PATH, sanitizer=sanitize_no_op, protocol="https", tags={}):

def connect(username, api_key, hostname=HOSTNAME, base_path=BASE_PATH, sanitizer=sanitize_no_op,
protocol="https", tags={}):
"""
Connect to Librato Metrics
"""
Expand All @@ -626,6 +626,7 @@ def _decode_body(resp):

return resp_data


def _getcharset(resp, default='utf-8'):
"""
Extract the charset from an HTTPResponse.
Expand All @@ -640,6 +641,7 @@ def _getcharset(resp, default='utf-8'):
m['content-type'] = resp.getheader('content-type')
return m.get_content_charset(default)


def _get_content_type(resp):
"""
Get Content-Type header ignoring parameters
Expand Down
15 changes: 2 additions & 13 deletions librato/aggregator.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,30 +44,26 @@ def __init__(self, connection, **args):
self.period = args.get('period')
self.measure_time = args.get('measure_time')


# Get a shallow copy of the top-level tag set
def get_tags(self):
return dict(self.tags)


# Define the top-level tag set for posting measurements
def set_tags(self, d):
self.tags = dict(d) # Create a copy


# Add one or more top-level tags for posting measurements
def add_tags(self, d):
self.tags.update(d)


def add(self, name, value):
if name not in self.measurements:
self.measurements[name] = {
'count': 1,
'sum': value,
'min': value,
'max': value
}
}
else:
m = self.measurements[name]
m['sum'] += value
Expand All @@ -79,15 +75,14 @@ def add(self, name, value):

return self.measurements


def add_tagged(self, name, value):
if name not in self.tagged_measurements:
self.tagged_measurements[name] = {
'count': 1,
'sum': value,
'min': value,
'max': value
}
}
else:
m = self.tagged_measurements[name]
m['sum'] += value
Expand All @@ -99,7 +94,6 @@ def add_tagged(self, name, value):

return self.tagged_measurements


def to_payload(self):
# Map measurements into Librato POST (array) format
# {
Expand Down Expand Up @@ -130,7 +124,6 @@ def to_payload(self):

return result


def to_md_payload(self):
# Map measurements into Librato MD POST format
# {
Expand Down Expand Up @@ -158,7 +151,6 @@ def to_md_payload(self):

return result


# Get/set the measure time if it is ever queried, that way you'll know the measure_time
# that was submitted, and we'll guarantee the same measure_time for all measurements
# extracted into a queue
Expand All @@ -168,7 +160,6 @@ def get_measure_time(self):
self.measure_time = mt
return self.measure_time


# Return floored measure time if period is set
# otherwise return user specified value if set
# otherwise return none
Expand All @@ -186,13 +177,11 @@ def floor_measure_time(self):
# Use the user-specified value with no flooring
return self.measure_time


def clear(self):
self.measurements = {}
self.tagged_measurements = {}
self.measure_time = None


def submit(self):
# Submit any legacy or tagged measurements to API
# This will actually return an empty 200 response (no body)
Expand Down
8 changes: 5 additions & 3 deletions librato/alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ class Alert(object):
"""Librato Alert Base class"""

def __init__(self, connection, name, _id=None, description=None, version=2,
conditions=[], services=[], attributes={}, active=True, rearm_seconds=None):
conditions=[], services=[], attributes={}, active=True, rearm_seconds=None):
self.connection = connection
self.name = name
self.description = description
Expand Down Expand Up @@ -67,6 +67,7 @@ def get_payload(self):
def save(self):
self.connection.update_alert(self)


class Condition(object):
ABOVE = 'above'
BELOW = 'below'
Expand Down Expand Up @@ -129,8 +130,8 @@ def from_dict(cls, data):

def get_payload(self):
obj = {'condition_type': self.condition_type,
'metric_name': self.metric_name,
'source': self.source}
'metric_name': self.metric_name,
'source': self.source}
if self.condition_type in [self.ABOVE, self.BELOW]:
obj['threshold'] = self.threshold
obj['summary_function'] = self.summary_function
Expand All @@ -140,6 +141,7 @@ def get_payload(self):
obj['duration'] = self._duration
return obj


class Service(object):
def __init__(self, _id, title=None, type=None, settings=None):
self._id = _id
Expand Down
6 changes: 3 additions & 3 deletions librato/annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
class Annotation(object):
"""Librato Annotation Stream Base class"""

def __init__(self, connection, name, display_name=None ):
def __init__(self, connection, name, display_name=None):
self.connection = connection
self.name = name
self.display_name = display_name
Expand All @@ -44,5 +44,5 @@ def from_dict(cls, connection, data):
obj.query = data['query'] if 'query' in data else {}
return obj

def get_payload(self):
return {'name': self.name,'display_name': self.display_name}
def get_payload(self):
return {'name': self.name, 'display_name': self.display_name}
1 change: 1 addition & 0 deletions librato/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ def __init__(self, msg=None):
404: NotFound
}


# http://dev.librato.com/v1/responses-errors
def get(code, resp_data):
if code in CODES:
Expand Down
7 changes: 4 additions & 3 deletions librato/instruments.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from librato.streams import Stream


class Instrument(object):
"""Librato Instrument Base class"""

Expand Down Expand Up @@ -47,9 +48,9 @@ def is_persisted(self):
def save(self):
if not self.is_persisted():
dummy_inst = self.connection.create_instrument(
self.name,
attributes=self.attributes,
streams=self.streams_payload())
self.name,
attributes=self.attributes,
streams=self.streams_payload())
self.id = dummy_inst.id
else:
self.connection.update_instrument(self)
3 changes: 1 addition & 2 deletions librato/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
class Metric(object):
"""Librato Metric Base class"""

def __init__(self, connection, name, attributes=None, period=None, description=None ):
def __init__(self, connection, name, attributes=None, period=None, description=None):
self.connection = connection
self.name = name
self.attributes = attributes or {}
Expand Down Expand Up @@ -88,4 +88,3 @@ def add(self, value, source=None, **params):

def what_am_i(self):
return 'counters'

5 changes: 3 additions & 2 deletions librato/queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ def _add_measurement(self, type, nm):
self.chunks[-1][type + 's'].append(nm)

def _add_tagged_measurement(self, nm):
if not self.tagged_chunks or self._num_measurements_in_current_chunk(tagged=True) == self.MAX_MEASUREMENTS_PER_CHUNK:
if (not self.tagged_chunks or
self._num_measurements_in_current_chunk(tagged=True) == self.MAX_MEASUREMENTS_PER_CHUNK):
self.tagged_chunks.append({'measurements': []})
self.tagged_chunks[-1]['measurements'].append(nm)

Expand Down Expand Up @@ -183,5 +184,5 @@ def _num_measurements_in_queue(self):
num += self._num_measurements_in_current_chunk() + self.MAX_MEASUREMENTS_PER_CHUNK * (len(self.chunks) - 1)
if self.tagged_chunks:
num += (self._num_measurements_in_current_chunk(tagged=True) +
self.MAX_MEASUREMENTS_PER_CHUNK * (len(self.tagged_chunks) - 1))
self.MAX_MEASUREMENTS_PER_CHUNK * (len(self.tagged_chunks) - 1))
return num
8 changes: 4 additions & 4 deletions librato/spaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ def add_bignumber_chart(self, name, metric, source='*',
'summary_function': summary_function
}
chart = self.add_chart(name,
type='bignumber',
use_last_value=use_last_value,
streams=[stream])
type='bignumber',
use_last_value=use_last_value,
streams=[stream])
return chart

# This currently only updates the name of the Space
Expand Down Expand Up @@ -177,7 +177,7 @@ def space(self):

def known_attributes(self):
return ['min', 'max', 'label', 'use_log_yaxis', 'use_last_value',
'related_space']
'related_space']

def get_payload(self):
# Set up the things that we aren't considering just "attributes"
Expand Down
Loading

0 comments on commit 3f23616

Please sign in to comment.