Debian Codegraph @

lang/py3/avro/tests/sample_http_server.py

raw
1 #!/usr/bin/env python3
2 # -*- mode: python -*-
3 # -*- coding: utf-8 -*-
4
5 # Licensed to the Apache Software Foundation (ASF) under one
6 # or more contributor license agreements. See the NOTICE file
7 # distributed with this work for additional information
8 # regarding copyright ownership. The ASF licenses this file
9 # to you under the Apache License, Version 2.0 (the
10 # "License"); you may not use this file except in compliance
11 # with the License. You may obtain a copy of the License at
12 #
13 # http://www.apache.org/licenses/LICENSE-2.0
14 #
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
20 from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
21 from avro import ipc
22 from avro import protocol
23
24 MAIL_PROTOCOL_JSON = """\
25 {"namespace": "example.proto",
26 "protocol": "Mail",
27
28 "types": [
29 {"name": "Message", "type": "record",
30 "fields": [
31 {"name": "to", "type": "string"},
32 {"name": "from", "type": "string"},
33 {"name": "body", "type": "string"}
34 ]
35 }
36 ],
37
38 "messages": {
39 "send": {
40 "request": [{"name": "message", "type": "Message"}],
41 "response": "string"
42 },
43 "replay": {
44 "request": [],
45 "response": "string"
46 }
47 }
48 }
49 """
50 MAIL_PROTOCOL = protocol.Parse(MAIL_PROTOCOL_JSON)
51 SERVER_ADDRESS = ('localhost', 9090)
52
53 class MailResponder(ipc.Responder):
54 def __init__(self):
55 ipc.Responder.__init__(self, MAIL_PROTOCOL)
56
57 def invoke(self, message, request):
58 if message.name == 'send':
59 request_content = request['message']
60 response = "Sent message to %(to)s from %(from)s with body %(body)s" % \
61 request_content
62 return response
63 elif message.name == 'replay':
64 return 'replay'
65
66 class MailHandler(BaseHTTPRequestHandler):
67 def do_POST(self):
68 self.responder = MailResponder()
69 call_request_reader = ipc.FramedReader(self.rfile)
70 call_request = call_request_reader.read_framed_message()
71 resp_body = self.responder.respond(call_request)
72 self.send_response(200)
73 self.send_header('Content-Type', 'avro/binary')
74 self.end_headers()
75 resp_writer = ipc.FramedWriter(self.wfile)
76 resp_writer.write_framed_message(resp_body)
77
78 if __name__ == '__main__':
79 mail_server = HTTPServer(SERVER_ADDRESS, MailHandler)
80 mail_server.allow_reuse_address = True
81 mail_server.serve_forever()