~didrocks/unity/altf10

« back to all changes in this revision

Viewing changes to grackle/client.py

  • Committer: Curtis Hovey
  • Date: 2012-02-24 21:31:01 UTC
  • Revision ID: curtis.hovey@canonical.com-20120224213101-jac3b2aj4nd5uwpj
Separate gracle MemoryStore to its own module.

Show diffs side-by-side

added added

removed removed

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