~didrocks/unity/altf10

« back to all changes in this revision

Viewing changes to grackle/client.py

  • Committer: Aaron Bentley
  • Date: 2012-01-10 10:46:26 UTC
  • Revision ID: aaron@canonical.com-20120110104626-39ehw9nhnzdzggtw
Add README and LICENSE

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import httplib
2
 
import simplejson
3
 
from urlparse import urlunparse
4
 
from urllib import (
5
 
    quote,
6
 
    urlencode,
7
 
)
8
 
 
9
 
 
10
 
 
11
 
class GrackleClient:
12
 
 
13
 
    def __init__(self, host, port):
14
 
        self.host = host
15
 
        self.port = port
16
 
        self.netloc = '%s:%d' % (host, port)
17
 
 
18
 
    def archive_url(self, archive_name, query):
19
 
        path = '/%s' % quote(archive_name)
20
 
        query = urlencode(query)
21
 
        return urlunparse(('http', self.netloc, path, '', query, ''))
22
 
 
23
 
    def _get_connection(self):
24
 
        print 'Connecting to %s' % self.port
25
 
        return httplib.HTTPConnection(self.host, self.port)
26
 
 
27
 
    def _verb_archive(self, verb, archive_name, query, body=None):
28
 
        url = self.archive_url(archive_name, query)
29
 
        print "URL: %s" % url
30
 
        connection = self._get_connection()
31
 
        connection.request(verb, url, body)
32
 
        return connection.getresponse()
33
 
 
34
 
    def put_message(self, archive_name, key, file_obj):
35
 
        response = self._verb_archive(
36
 
            'POST', archive_name, {'key': key}, file_obj.read())
37
 
        data = response.read()
38
 
        if response.status == httplib.BAD_REQUEST:
39
 
            raise Exception('wtf')
40
 
        elif response.status == httplib.CREATED:
41
 
            return
42
 
        else:
43
 
            raise Exception('!!')
44
 
 
45
 
    def get_messages(self, archive_name, message_ids=None):
46
 
        parameters = {}
47
 
        if message_ids is not None:
48
 
            parameters['message_ids'] = message_ids
49
 
        query = {'parameters': simplejson.dumps(parameters)}
50
 
        response = self._verb_archive('GET', archive_name, query)
51
 
        data = response.read()
52
 
        return simplejson.loads(data)