Skip to content

Instantly share code, notes, and snippets.

@charignon
Created January 3, 2016 23:40
Show Gist options
  • Save charignon/d6fcbe6d99d0c4331d2a to your computer and use it in GitHub Desktop.
Save charignon/d6fcbe6d99d0c4331d2a to your computer and use it in GitHub Desktop.
# Script to query the numerous API
# make sure that your API key is set in the apikey file
import json
import os
import sys
import argparse
import requests
from termcolor import cprint
from requests.auth import HTTPBasicAuth
if not os.path.exists("apikey"):
cprint("File not found 'apikey', please create this file with your API KEY",
"red",
file=sys.stderr)
sys.exit(1)
with open("apikey") as f:
apikey = f.read().strip()
auth = HTTPBasicAuth(apikey, '')
GETALLURL = 'https://api.numerousapp.com/v1/users/me/metrics'
class Metric(object):
@classmethod
def fromjson(cls, entry):
value = entry['value']
url = entry['links']['self']+"/events"
label = entry['label']
return Metric(value, url, label)
def __init__(self, value, url, label):
self._value = value
self.value = value
self.url = url
self.dirty = False
self.label = label
def update(self, newvalue):
self.value = newvalue
self._updatevalue()
def increment(self):
self.update(self.value + 1)
def decrement(self):
self.update(self.value - 1)
def _updatevalue(self):
if self._value != self.value:
cprint("Updating metric %s from %s to %s"
% (self.label, self._value, self.value),
"green")
requests.post(self.url, data=json.dumps({'value':self.value}), auth=auth)
@classmethod
def getAll(cls):
r = requests.get(GETALLURL, auth=auth)
return [Metric.fromjson(entry) for entry in r.json()]
def __repr__(self):
return "<%s:%s>" % (self.label, self.value)
def checkargs(args):
"""Sanity check the arguments"""
if (args.increment, args.decrement, args.list, args.update).count(True) != 1:
cprint("Specify only one of increment/decrement/list/update",
"red",
file=sys.stderr)
sys.exit(1)
if (args.update and args.value is None):
cprint("With --update, give a value with --value",
"red",
file=sys.stderr)
sys.exit(1)
if (not args.list and not args.metric):
cprint("Without --list, you need to give a metric name",
"red",
file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description='Interact with the numerous API')
parser.add_argument('--increment', action="store_true")
parser.add_argument('--decrement', action="store_true")
parser.add_argument('--update', action="store_true")
parser.add_argument('--list', action="store_true", help="print all metrics as JSON")
parser.add_argument('--value', type=int)
parser.add_argument('--metric', type=str)
args = parser.parse_args()
checkargs(args)
# Print all the metrics
if args.list:
metrics = Metric.getAll()
print json.dumps([{"label": m.label, "value":m.value} for m in metrics])
sys.exit(0)
# Update the value
metrics = Metric.getAll()
previousValue = None
for metric in metrics:
if metric.label == args.metric:
previousValue = metric.value
if args.increment:
metric.increment()
elif args.decrement:
metric.decrement()
elif args.update:
metric.update(args.value)
break
# Sanity check: the value has been found
if previousValue is None:
cprint("Metric not found, please check metric name %s, available names %s"
% (args.metric, [m.label for m in metrics]), "red", file=sys.stderr)
sys.exit(1)
# Check that the value has been updated
metrics = Metric.getAll()
for metric in metrics:
if metric.label == args.metric:
if metric.value == previousValue:
cprint("Updated created no change, make sure you are doing the right thing",
"red", file=sys.stderr)
break
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment