blob: f5771922ef9433b4bf54b6882dd99a30385b4cd2 [file] [log] [blame]
Mark Slee89e2bb82007-03-01 00:20:36 +00001# 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
Mark Sleebd8b9912007-02-27 20:17:00 +00007from TTransport import *
8from cStringIO import StringIO
9
10import httplib
11
12class THttpClient(TTransportBase):
13
14 """Http implementation of TTransport base."""
15
16 def __init__(self, host, port, uri):
17 self.host = host
18 self.port = port
19 self.uri = uri
20 self.__wbuf = StringIO()
21 self.__http = None
22
23 def open(self):
24 self.__http = httplib.HTTP(self.host, self.port)
25
26 def close(self):
27 self.__http.close()
28 self.__http = None
David Reiss0c90f6f2008-02-06 22:18:40 +000029
Mark Sleebd8b9912007-02-27 20:17:00 +000030 def isOpen(self):
31 return self.__http != None
32
33 def read(self, sz):
34 return self.__http.file.read(sz)
35
36 def write(self, buf):
37 self.__wbuf.write(buf)
38
39 def flush(self):
David Reiss7c1f6f82009-03-24 20:10:24 +000040 if self.isOpen():
41 self.close()
42 self.open();
43
Mark Sleebd8b9912007-02-27 20:17:00 +000044 # Pull data out of buffer
45 data = self.__wbuf.getvalue()
46 self.__wbuf = StringIO()
47
48 # HTTP request
49 self.__http.putrequest('POST', self.uri)
50
51 # Write headers
52 self.__http.putheader('Host', self.host)
53 self.__http.putheader('Content-Type', 'application/x-thrift')
54 self.__http.putheader('Content-Length', str(len(data)))
55 self.__http.endheaders()
56
57 # Write payload
58 self.__http.send(data)
59
60 # Get reply to flush the request
61 self.code, self.message, self.headers = self.__http.getreply()