~didrocks/unity/altf10

« back to all changes in this revision

Viewing changes to grackle/service.py

  • Committer: Curtis Hovey
  • Date: 2012-03-17 22:45:15 UTC
  • Revision ID: curtis.hovey@canonical.com-20120317224515-r2n23tqc8cx7cul4
Only store the unique information needed by grackle.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
__metaclass__ = type
 
2
__all__ = [
 
3
    'ForkedFakeService',
 
4
    'GrackleService',
 
5
    ]
2
6
 
3
7
import httplib
4
8
import logging
14
18
 
15
19
 
16
20
class GrackleService:
17
 
    """A request handler that forwards to server.store."""
 
21
    """A request handler that forwards to an archive store."""
18
22
 
19
23
    def __init__(self, store):
20
24
        self.store = store
24
28
        self.environ = environ
25
29
        self.start_response = start_response
26
30
        self.method = environ['REQUEST_METHOD']
27
 
        self.host_port = shift_path_info(environ)
28
 
        self.application = shift_path_info(environ)
29
 
        self.path = environ['PATH_INFO'].split('/')[1:]
 
31
        if '://' in environ['PATH_INFO']:
 
32
            # All the needed information is embedded in PATH_INFO.
 
33
            shift_path_info(environ)  # shift the host and or port.
 
34
            self.application = shift_path_info(environ)
 
35
            path = environ['PATH_INFO'].split('/')
 
36
            path.pop(0)  # Pop the scheme.
 
37
            self.path = path
 
38
        elif environ['SCRIPT_NAME'] == '':
 
39
            # Remove the application to set the path.
 
40
            self.application = shift_path_info(environ)
 
41
            self.path = environ['PATH_INFO'].split('/')
 
42
        else:
 
43
            self.application = environ['SCRIPT_NAME']
 
44
            self.path = environ['PATH_INFO'].split('/')
30
45
        self.query_string = environ['QUERY_STRING']
31
46
        return self.handle_request()
32
47
 
33
48
    def handle_request(self):
34
 
        if self.method == 'PUT':
 
49
        """Select the method to handle the request and return a response."""
 
50
        if self.application != 'archive':
 
51
            return self.send_response(httplib.NOT_FOUND)
 
52
        elif self.method == 'PUT':
35
53
            return self.do_PUT()
36
 
        if self.method == 'POST':
 
54
        elif self.method == 'POST':
37
55
            return self.do_POST()
38
 
        if self.method == 'GET':
 
56
        elif self.method == 'GET':
39
57
            return self.do_GET()
 
58
        return self.send_response(httplib.METHOD_NOT_ALLOWED)
40
59
 
41
 
    def send_response(self, code, headers={}, reason=None):
 
60
    def send_response(self, code, response='', reason=None, headers={}):
 
61
        """Set the status code and reason, then return the response."""
42
62
        if reason is None:
43
63
            reason = httplib.responses[code]
44
 
        response_code = '%s %s' % (code, reason)
 
64
        response_status = '%s %s' % (code, reason)
45
65
        response_headers = {'content-type': 'application/json'}
46
66
        response_headers.update(headers.items())
47
 
        self.start_response(response_code, response_headers.items())
 
67
        self.start_response(response_status, response_headers.items())
 
68
        return [response]
48
69
 
49
70
    def do_PUT(self):
50
71
        """Create an archive or message on PUT."""
52
73
            # This expected path is /archive/archive_id.
53
74
            try:
54
75
                self.store.put_archive(self.path[0])
55
 
                self.send_response(httplib.CREATED)
56
 
                return ['']
 
76
                return self.send_response(httplib.CREATED)
57
77
            except Exception, error:
58
 
                self.send_response(
 
78
                return self.send_response(
59
79
                    httplib.BAD_REQUEST, reason=error.__doc__)
60
 
                return ['']
61
 
        if len(self.path) == 2:
 
80
        elif len(self.path) == 2:
62
81
            # This expected path is /archive/archive_id/message_id.
63
82
            try:
64
83
                put_input = self.environ['wsgi.input']
65
84
                message = put_input.read(int(self.environ['CONTENT_LENGTH']))
66
85
                self.store.put_message(self.path[0], self.path[1], message)
67
 
                self.send_response(httplib.CREATED)
68
 
                return ['']
69
 
            except:
70
 
                self.send_response(httplib.BAD_REQUEST)
71
 
                return ['']
 
86
                return self.send_response(httplib.CREATED)
 
87
            except Exception, error:
 
88
                return self.send_response(
 
89
                    httplib.BAD_REQUEST, reason=error.__doc__)
72
90
 
73
91
    def do_POST(self):
74
92
        """Change a message on POST."""
78
96
                # This expected path is /archive/archive_id/message_id.
79
97
                response = self.store.hide_message(
80
98
                    self.path[0], self.path[1], self.query_string)
81
 
                self.send_response(httplib.OK)
82
 
                return [simplejson.dumps(response)]
83
 
            except:
84
 
                self.send_response(httplib.BAD_REQUEST)
85
 
                return ['']
 
99
                response = simplejson.dumps(response)
 
100
                return self.send_response(httplib.OK, response=response)
 
101
            except Exception, error:
 
102
                return self.send_response(
 
103
                    httplib.BAD_REQUEST, reason=error.__doc__)
86
104
 
87
105
    def do_GET(self):
88
106
        """Retrieve a list of messages on GET."""
89
107
        try:
90
108
            response = self.store.get_messages(
91
109
                self.path[0], self.query_string)
92
 
            self.send_response(httplib.OK)
93
 
            return [simplejson.dumps(response)]
 
110
            response = simplejson.dumps(response)
 
111
            return self.send_response(httplib.OK, response=response)
94
112
        except Exception, error:
95
 
            self.send_response(httplib.BAD_REQUEST, reason=error.__doc__)
96
 
            return ['']
 
113
            return self.send_response(
 
114
                httplib.BAD_REQUEST, reason=error.__doc__)
97
115
 
98
116
    def log_message(self, format, *args):
99
117
        """Override log_message to use standard Python logging."""
164
182
        os.kill(self.pid, SIGKILL)
165
183
 
166
184
 
167
 
def application(environ, start_response):
168
 
    start_response('200 OK', [('Content-Type', 'text/plain')])
169
 
    return "Hello World"
170
 
 
171
 
 
172
185
if __name__ == '__main__':
173
186
    app = GrackleService(MemoryStore({}))
174
187
    service = make_server('', 8787, app)