Permalink
Browse files

first commit on a python client

  • Loading branch information...
0 parents commit d447000f3855081ce95505ffd0bcb44cf4ed3a1e @tnm committed Dec 24, 2010
Showing with 106 additions and 0 deletions.
  1. +3 −0 README
  2. +59 −0 pydiner.py
  3. +44 −0 tests.py
3 README
@@ -0,0 +1,3 @@
+python client for diner
+
+bsd license
@@ -0,0 +1,59 @@
+import urllib
+import urllib2
+from urllib2 import HTTPError
+
+BASE_URL = "http://localhost:4567"
+
+class DinerError(Exception):
+ def __init__(self, msg, error_code=None):
+ self.msg = msg
+
+ def __str__(self):
+ return repr(self.msg)
+
+class Diner(object):
+ def __init__(self, key):
+ self.key = key
+
+ def incr(self, element, score):
+ url = '%s/%s' % (BASE_URL, self.key)
+ params = {
+ 'element': element,
+ 'score': score,
+ 'command': 'increment'
+ }
+
+ try:
+ data = urllib.urlencode(params)
+ req = urllib2.Request(url, data)
+ response = urllib2.urlopen(req).read()
+ return response
+ except HTTPError, e:
+ raise DinerError("Didn't increment. %s" %(e))
+
+ def card(self):
+ url = '%s/%s?command=%s' % (BASE_URL, self.key, 'card')
+ try:
+ response = urllib2.urlopen(url).read()
+ return response
+ except HTTPError, e:
+ raise DinerError("Didn't return cardinality. %s" %(e))
+
+ def rank(self, element):
+ url = '%s/%s?command=%s&element=%s' % (BASE_URL, self.key, 'rank', element)
+ try:
+ response = urllib2.urlopen(url).read()
+ return response
+ except HTTPError, e:
+ raise DinerError("Didn't return rank. %s" %(e))
+
+ def score(self, element):
+ url = '%s/%s?command=%s&element=%s' % (BASE_URL, self.key, 'score', element)
+ try:
+ response = urllib2.urlopen(url).read()
+ return response
+ except HTTPError, e:
+ raise DinerError("Didn't return score. %s" %(e))
+
+
+
@@ -0,0 +1,44 @@
+import unittest
+from pydiner import Diner
+import redis
+
+r = redis.Redis()
+
+class TestIncrement(unittest.TestCase):
+ def setUp(self):
+ self.diner = Diner(key='awesometestkey')
+ self.diner.incr('awesometestvalue', 10)
+
+ def tearDown(self):
+ r.delete('diner:awesometestkey')
+
+ def test_creation(self):
+ self.assertEquals(r.exists('diner:awesometestkey'), True)
+
+ def test_increment(self):
+ diner = self.diner
+ self.assertEquals(r.zscore('diner:awesometestkey', 'awesometestvalue'), 10)
+
+class TestRank(unittest.TestCase):
+ def setUp(self):
+ self.diner = Diner(key='awesometestkey3')
+ self.diner.incr('awesometestvalue1', 20)
+ self.diner.incr('awesometestvalue2', 40)
+ self.diner.incr('awesometestvalue3', 100)
+
+ def tearDown(self):
+ r.delete('diner:awesometestkey3')
+
+ def test_rank(self):
+ diner = self.diner
+ self.assertEquals(diner.rank('awesometestvalue2'),
+ '[{"diner_key":"awesometestkey3"},{"rank":1,"element":"awesometestvalue2"}]')
+
+
+
+
+if __name__ == '__main__':
+ unittest.main()
+
+
+

0 comments on commit d447000

Please sign in to comment.