~unity-2d-team/unity-2d/Shell-MultiMonitor

« back to all changes in this revision

Viewing changes to grackle/client.py

  • Committer: Curtis Hovey
  • Date: 2012-02-14 21:55:15 UTC
  • mto: This revision was merged to the branch mainline in revision 45.
  • Revision ID: curtis.hovey@canonical.com-20120214215515-vu1zn9n58ov659es
Added basic handling of date_range.

Show diffs side-by-side

added added

removed removed

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