David Reiss | f78ec2b | 2009-01-31 21:59:32 +0000 | [diff] [blame] | 1 | # Copyright (c) 2006- Facebook |
| 2 | # Distributed under the Thrift Software License |
| 3 | # |
| 4 | # See accompanying file LICENSE or visit the Thrift site at: |
| 5 | # http://developers.facebook.com/thrift/ |
| 6 | |
| 7 | import BaseHTTPServer |
| 8 | |
| 9 | from thrift.server import TServer |
| 10 | from thrift.transport import TTransport |
| 11 | |
| 12 | class THttpServer(TServer.TServer): |
| 13 | """A simple HTTP-based Thrift server |
| 14 | |
| 15 | This class is not very performant, but it is useful (for example) for |
| 16 | acting as a mock version of an Apache-based PHP Thrift endpoint.""" |
| 17 | |
| 18 | def __init__(self, processor, server_address, |
| 19 | inputProtocolFactory, outputProtocolFactory = None): |
| 20 | """Set up protocol factories and HTTP server. |
| 21 | |
| 22 | See BaseHTTPServer for server_address. |
| 23 | See TServer for protocol factories.""" |
| 24 | |
| 25 | if outputProtocolFactory is None: |
| 26 | outputProtocolFactory = inputProtocolFactory |
| 27 | |
| 28 | TServer.TServer.__init__(self, processor, None, None, None, |
| 29 | inputProtocolFactory, outputProtocolFactory) |
| 30 | |
| 31 | thttpserver = self |
| 32 | |
| 33 | class RequestHander(BaseHTTPServer.BaseHTTPRequestHandler): |
| 34 | def do_POST(self): |
| 35 | # Don't care about the request path. |
| 36 | self.send_response(200) |
| 37 | self.send_header("content-type", "application/x-thrift") |
| 38 | self.end_headers() |
| 39 | |
| 40 | itrans = TTransport.TFileObjectTransport(self.rfile) |
| 41 | otrans = TTransport.TFileObjectTransport(self.wfile) |
| 42 | iprot = thttpserver.inputProtocolFactory.getProtocol(itrans) |
| 43 | oprot = thttpserver.outputProtocolFactory.getProtocol(otrans) |
| 44 | thttpserver.processor.process(iprot, oprot) |
| 45 | otrans.flush() |
| 46 | |
| 47 | self.httpd = BaseHTTPServer.HTTPServer(server_address, RequestHander) |
| 48 | |
| 49 | def serve(self): |
| 50 | self.httpd.serve_forever() |