blob: 9bf80cbb87384406d8025c930547c0e761032a1a [file] [log] [blame]
David Reissf78ec2b2009-01-31 21:59:32 +00001#
David Reissea2cba82009-03-30 21:35:00 +00002# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18#
David Reissf78ec2b2009-01-31 21:59:32 +000019
20import BaseHTTPServer
21
22from thrift.server import TServer
23from thrift.transport import TTransport
24
25class THttpServer(TServer.TServer):
26 """A simple HTTP-based Thrift server
27
28 This class is not very performant, but it is useful (for example) for
29 acting as a mock version of an Apache-based PHP Thrift endpoint."""
30
31 def __init__(self, processor, server_address,
Bryan Duxburyd6a02ff2010-09-02 15:14:27 +000032 inputProtocolFactory, outputProtocolFactory = None,
33 server_class = BaseHTTPServer.HTTPServer):
David Reissf78ec2b2009-01-31 21:59:32 +000034 """Set up protocol factories and HTTP server.
35
36 See BaseHTTPServer for server_address.
37 See TServer for protocol factories."""
38
39 if outputProtocolFactory is None:
40 outputProtocolFactory = inputProtocolFactory
41
42 TServer.TServer.__init__(self, processor, None, None, None,
43 inputProtocolFactory, outputProtocolFactory)
44
45 thttpserver = self
46
47 class RequestHander(BaseHTTPServer.BaseHTTPRequestHandler):
48 def do_POST(self):
49 # Don't care about the request path.
50 self.send_response(200)
51 self.send_header("content-type", "application/x-thrift")
52 self.end_headers()
53
54 itrans = TTransport.TFileObjectTransport(self.rfile)
55 otrans = TTransport.TFileObjectTransport(self.wfile)
Bryan Duxburyd6a02ff2010-09-02 15:14:27 +000056 itrans = TTransport.TBufferedTransport(itrans, int(self.headers['Content-Length']))
57 otrans = TTransport.TBufferedTransport(otrans)
David Reissf78ec2b2009-01-31 21:59:32 +000058 iprot = thttpserver.inputProtocolFactory.getProtocol(itrans)
59 oprot = thttpserver.outputProtocolFactory.getProtocol(otrans)
60 thttpserver.processor.process(iprot, oprot)
61 otrans.flush()
62
Bryan Duxburyd6a02ff2010-09-02 15:14:27 +000063 self.httpd = server_class(server_address, RequestHander)
David Reissf78ec2b2009-01-31 21:59:32 +000064
65 def serve(self):
66 self.httpd.serve_forever()