~didrocks/unity/altf10

6 by Aaron Bentley
Use constants.
1
import httplib
11 by Aaron Bentley
Start working on GET.
2
import simplejson
3
from urlparse import urlunparse
4
from urllib import (
5
    quote,
6
    urlencode,
7
)
8
7 by Aaron Bentley
Fix URLs etc.
9
10
11
class GrackleClient:
12
13
    def __init__(self, host, port):
14
        self.host = host
15
        self.port = port
11 by Aaron Bentley
Start working on GET.
16
        self.netloc = '%s:%d' % (host, port)
17
18 by Aaron Bentley
archive_name -> archive_id
18
    def archive_url(self, archive_id, query):
19
        path = '/%s' % quote(archive_id)
15 by Aaron Bentley
Test filtering by message-id.
20
        query_string = urlencode(query)
21
        return urlunparse(('http', self.netloc, path, '', query_string, ''))
11 by Aaron Bentley
Start working on GET.
22
23
    def _get_connection(self):
24
        return httplib.HTTPConnection(self.host, self.port)
25
18 by Aaron Bentley
archive_name -> archive_id
26
    def _verb_archive(self, verb, archive_id, query, body=None):
27
        url = self.archive_url(archive_id, query)
11 by Aaron Bentley
Start working on GET.
28
        connection = self._get_connection()
29
        connection.request(verb, url, body)
30
        return connection.getresponse()
31
18 by Aaron Bentley
archive_name -> archive_id
32
    def put_message(self, archive_id, key, file_obj):
11 by Aaron Bentley
Start working on GET.
33
        response = self._verb_archive(
18 by Aaron Bentley
archive_name -> archive_id
34
            'POST', archive_id, {'key': key}, file_obj.read())
7 by Aaron Bentley
Fix URLs etc.
35
        data = response.read()
36
        if response.status == httplib.BAD_REQUEST:
37
            raise Exception('wtf')
38
        elif response.status == httplib.CREATED:
39
            return
40
        else:
41
            raise Exception('!!')
11 by Aaron Bentley
Start working on GET.
42
19 by Aaron Bentley
Implement memo/limit support.
43
    def get_messages(self, archive_id, message_ids=None, limit=None,
20 by Aaron Bentley
Support order by date
44
                     memo=None, order=None):
11 by Aaron Bentley
Start working on GET.
45
        parameters = {}
46
        if message_ids is not None:
13 by Aaron Bentley
Retrieve messages.
47
            parameters['message_ids'] = message_ids
19 by Aaron Bentley
Implement memo/limit support.
48
        if limit is not None:
49
            parameters['limit'] = limit
50
        if memo is not None:
51
            parameters['memo'] = memo
20 by Aaron Bentley
Support order by date
52
        if order is not None:
53
            parameters['order'] = order
11 by Aaron Bentley
Start working on GET.
54
        query = {'parameters': simplejson.dumps(parameters)}
18 by Aaron Bentley
archive_name -> archive_id
55
        response = self._verb_archive('GET', archive_id, query)
13 by Aaron Bentley
Retrieve messages.
56
        data = response.read()
57
        return simplejson.loads(data)