| Mark Slee | 89e2bb8 | 2007-03-01 00:20:36 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python | 
|  | 2 | # | 
|  | 3 | # Copyright (c) 2006- Facebook | 
|  | 4 | # Distributed under the Thrift Software License | 
|  | 5 | # | 
|  | 6 | # See accompanying file LICENSE or visit the Thrift site at: | 
|  | 7 | # http://developers.facebook.com/thrift/ | 
|  | 8 |  | 
| Mark Slee | bd8b991 | 2007-02-27 20:17:00 +0000 | [diff] [blame] | 9 | from TTransport import * | 
|  | 10 | from cStringIO import StringIO | 
|  | 11 |  | 
|  | 12 | import httplib | 
|  | 13 |  | 
|  | 14 | class THttpClient(TTransportBase): | 
|  | 15 |  | 
|  | 16 | """Http implementation of TTransport base.""" | 
|  | 17 |  | 
|  | 18 | def __init__(self, host, port, uri): | 
|  | 19 | self.host = host | 
|  | 20 | self.port = port | 
|  | 21 | self.uri = uri | 
|  | 22 | self.__wbuf = StringIO() | 
|  | 23 | self.__http = None | 
|  | 24 |  | 
|  | 25 | def open(self): | 
|  | 26 | self.__http = httplib.HTTP(self.host, self.port) | 
|  | 27 |  | 
|  | 28 | def close(self): | 
|  | 29 | self.__http.close() | 
|  | 30 | self.__http = None | 
|  | 31 |  | 
|  | 32 | def isOpen(self): | 
|  | 33 | return self.__http != None | 
|  | 34 |  | 
|  | 35 | def read(self, sz): | 
|  | 36 | return self.__http.file.read(sz) | 
|  | 37 |  | 
|  | 38 | def write(self, buf): | 
|  | 39 | self.__wbuf.write(buf) | 
|  | 40 |  | 
|  | 41 | def flush(self): | 
|  | 42 | # Pull data out of buffer | 
|  | 43 | data = self.__wbuf.getvalue() | 
|  | 44 | self.__wbuf = StringIO() | 
|  | 45 |  | 
|  | 46 | # HTTP request | 
|  | 47 | self.__http.putrequest('POST', self.uri) | 
|  | 48 |  | 
|  | 49 | # Write headers | 
|  | 50 | self.__http.putheader('Host', self.host) | 
|  | 51 | self.__http.putheader('Content-Type', 'application/x-thrift') | 
|  | 52 | self.__http.putheader('Content-Length', str(len(data))) | 
|  | 53 | self.__http.endheaders() | 
|  | 54 |  | 
|  | 55 | # Write payload | 
|  | 56 | self.__http.send(data) | 
|  | 57 |  | 
|  | 58 | # Get reply to flush the request | 
|  | 59 | self.code, self.message, self.headers = self.__http.getreply() |