~didrocks/unity/altf10

« back to all changes in this revision

Viewing changes to grackle/client.py

  • Committer: Aaron Bentley
  • Date: 2012-01-11 14:04:41 UTC
  • Revision ID: aaron@canonical.com-20120111140441-l4sanxq1en07oblx
Test filtering by message-id.

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
    urlencode,
7
7
)
8
8
 
9
 
from grackle.error import (
10
 
    UnparsableDateRange,
11
 
    UnsupportedDisplayType,
12
 
    UnsupportedOrder,
13
 
    )
14
9
 
15
10
 
16
11
class GrackleClient:
17
 
    """Class for accessing Grackle web service."""
18
12
 
19
13
    def __init__(self, host, port):
20
 
        """Constructor.
21
 
 
22
 
        :param host: The name of the server.
23
 
        :param port: The port providing Grackle service.
24
 
        """
25
14
        self.host = host
26
15
        self.port = port
27
16
        self.netloc = '%s:%d' % (host, port)
28
17
 
29
 
    def archive_url(self, archive_id, query):
30
 
        """Return the URL for an archive
31
 
 
32
 
        :param archive_id: The id of the archive to generate the URL for.
33
 
        :param query: The query to use in the URL, as a dict.
34
 
        """
35
 
        path = '/archive/%s' % quote(archive_id)
 
18
    def archive_url(self, archive_name, query):
 
19
        path = '/%s' % quote(archive_name)
36
20
        query_string = urlencode(query)
37
21
        return urlunparse(('http', self.netloc, path, '', query_string, ''))
38
22
 
39
23
    def _get_connection(self):
40
24
        return httplib.HTTPConnection(self.host, self.port)
41
25
 
42
 
    def _method_archive(self, method, archive_id, query, body=None):
43
 
        """Perform an HTTP method on an archive's URL."""
44
 
        url = self.archive_url(archive_id, query)
 
26
    def _verb_archive(self, verb, archive_name, query, body=None):
 
27
        url = self.archive_url(archive_name, query)
45
28
        connection = self._get_connection()
46
 
        connection.request(method, url, body)
 
29
        connection.request(verb, url, body)
47
30
        return connection.getresponse()
48
31
 
49
 
    def put_message(self, archive_id, key, file_obj):
50
 
        """Put a message into an archive.
51
 
 
52
 
        :param archive_id: The archive to put the message into.
53
 
        :param key: An arbitrary identifier that can later be used to retrieve
54
 
            the message.
55
 
        :param file_obj: The raw text of the message, as a file.
56
 
        """
57
 
        response = self._method_archive(
58
 
            'POST', archive_id, {'key': key}, file_obj.read())
59
 
        response.read()
 
32
    def put_message(self, archive_name, key, file_obj):
 
33
        response = self._verb_archive(
 
34
            'POST', archive_name, {'key': key}, file_obj.read())
 
35
        data = response.read()
60
36
        if response.status == httplib.BAD_REQUEST:
61
37
            raise Exception('wtf')
62
38
        elif response.status == httplib.CREATED:
64
40
        else:
65
41
            raise Exception('!!')
66
42
 
67
 
    def get_messages(self, archive_id, message_ids=None, date_range=None,
68
 
                     limit=None, memo=None, order=None, headers=None,
69
 
                     include_hidden=False, max_body_length=None,
70
 
                     display_type='all'):
71
 
        """Retrieve specified messages.
72
 
 
73
 
        :param archive_id: The archive to retrieve messages from.
74
 
        :param message_ids: (optional) Retrieve only messages with these ids.
75
 
        :param date_range: Retrieve the messages from or between a range of
76
 
            dates. Example: 2012-01-01..2012-01-31 retrieve all the messages
77
 
            between the 01 and 31 of January, including message from 01
78
 
            and 31.
79
 
        :param limit: The maximum number of messages to return.  The server
80
 
            may, at its discretion, return fewer.
81
 
        :param memo: (optional) Opaque identifier describing the position in
82
 
            the list of messages to return.  The combination of a memo and a
83
 
            limit describes a batch of results.  If not specified, the start
84
 
            is used.
85
 
        :param order: The order to return results in.  Supported orders are
86
 
            determined by the server.  See test_client.SUPPORTED_ORDERS for an
87
 
            example.
88
 
        :param headers: The headers to include in the message.  Only headers
89
 
            actually present in the message will be provided.  If unspecified,
90
 
            most headers will be included.
91
 
        :param max_body_length: The maximum length for a message's body.  When
92
 
            multiple messages are nested (as with a thread), this applies to
93
 
            each message's body, not the aggregate length of all messages'
94
 
            bodies.
95
 
        :param include_hidden: If true, include messages that have been
96
 
            flagged "hidden" in the results.
97
 
        :param display_type: Adjust the message content to meet the needs of
98
 
            the intended display. Valid values are:
99
 
            all: (the default) include all message content.
100
 
            text-only: include only plain/text parts; exclude all other parts.
101
 
            headers-only: include only the message headers.
102
 
        """
 
43
    def get_messages(self, archive_name, message_ids=None):
103
44
        parameters = {}
104
45
        if message_ids is not None:
105
46
            parameters['message_ids'] = message_ids
106
 
        if date_range is not None:
107
 
            parameters['date_range'] = date_range
108
 
        if limit is not None:
109
 
            parameters['limit'] = limit
110
 
        if memo is not None:
111
 
            parameters['memo'] = memo
112
 
        if order is not None:
113
 
            parameters['order'] = order
114
 
        if headers is not None:
115
 
            parameters['headers'] = headers
116
 
        if max_body_length is not None:
117
 
            parameters['max_body_length'] = max_body_length
118
 
        parameters['display_type'] = display_type
119
 
        parameters['include_hidden'] = include_hidden
120
47
        query = {'parameters': simplejson.dumps(parameters)}
121
 
        response = self._method_archive('GET', archive_id, query)
122
 
        if response.status == httplib.BAD_REQUEST:
123
 
            if response.reason == UnsupportedOrder.__doc__:
124
 
                raise UnsupportedOrder
125
 
            elif response.reason == UnsupportedDisplayType.__doc__:
126
 
                raise UnsupportedDisplayType
127
 
            elif response.reason == UnparsableDateRange.__doc__:
128
 
                raise UnparsableDateRange
129
 
            else:
130
 
                raise ValueError('Bad request')
 
48
        response = self._verb_archive('GET', archive_name, query)
131
49
        data = response.read()
132
50
        return simplejson.loads(data)