def list_thrift_proto(self, struct_object, data_str, cur): self.un_tran_str = TranStr.UnTranStr(data_str,cur+4) if self.proto_type == 1: self.list_proto = TBinaryProtocol(self.un_tran_str) elif self.proto_type == 2: self.list_proto = TCompactProtocol(self.un_tran_str) data_dict = {} self.list_proto.readMessageBegin() data_dict = self.__un_tran_struct(struct_object) self.list_proto.readMessageEnd() return data_dict
def packTxId(agentid, starttime, sequence): # refer TransactionIdUtils.writeTransactionId() # byte:0, PrefixedString:agentid, VLong:time, VLong:sequence trans = TTransport.TMemoryBuffer() prot=TCompactProtocol.TCompactProtocol(trans) prot.state = TCompactProtocol.VALUE_WRITE prot.writeByte(0) prot.writeI32(len(agentid)) # this should be vlen(zigzag(int32)) trans.write(agentid) TCompactProtocol.writeVarint(trans, starttime) # this should be vlen(long), no zigzag, like BytesUtils.writeVar64() in java TCompactProtocol.writeVarint(trans, sequence) #printhex(trans.getvalue()) return trans.getvalue() # type is str
def thrift_proto(self, struct_object, data_dict, fun_name, mock_type): self.tran_str = TranStr.TranStr() print self.proto_type if self.proto_type == 1: self.protocol = TBinaryProtocol(self.tran_str) elif self.proto_type == 2: self.protocol = TCompactProtocol(self.tran_str) if mock_type == 2: self.protocol.writeMessageBegin(fun_name, TMessageType.CALL, 0) elif mock_type == 1: self.protocol.writeMessageBegin(fun_name, TMessageType.REPLY, 0) self.__tran_struct(struct_object, data_dict) self.protocol.writeMessageEnd() data_str = self.tran_str.get_protocol_str() data_str = struct.pack('!i',len(data_str)) + data_str return data_str
def __init__(self, host=u"192.168.2.41", port=8880): """ 构造器 :param host: (str) 域名或IP地址 :param port: (int) 端口 :return: (BloomFilterClient) """ #初始化连接,使用facebook的thrift框架,支持跨多门语言的RMI self.transport = TSocket.TSocket(host, port) self.transport = TTransport.TBufferedTransport(self.transport) protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = BloomFilterService.Client(protocol) #打开端口 self.transport.open()
def ready(self): """ After login, make `client` and `client_in` instance to communicate with LINE server """ #raise Exception("Code is removed because of the request of LINE corporation") self._headers['Connection'] = "keep-alive" self.transport = THttpClient.THttpClient(self.LINE_HTTP_IN_URL) self.transport_in = THttpClient.THttpClient(self.LINE_HTTP_IN_URL) self.transport.setCustomHeaders(self._headers) self.transport_in.setCustomHeaders(self._headers) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.protocol_in = TCompactProtocol.TCompactProtocol(self.transport_in) self._client = CurveThrift.Client(self.protocol) self._client_in = CurveThrift.Client(self.protocol_in) self.transport.open() self.transport_in.open()
def __init__(self, authToken): Config.__init__(self) self.transport = THttpClient.THttpClient(self.LINE_HOST_DOMAIN, None, self.LINE_API_QUERY_PATH_FIR) self.transport.path = self.LINE_AUTH_QUERY_PATH self.transport.setCustomHeaders({ "X-Line-Application": self.APP_NAME, "User-Agent": self.USER_AGENT, "X-Line-Access": authToken }) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = CallService.Client(self.protocol) self.transport.path = self.LINE_CALL_QUERY_PATH self.transport.open()
def GetShardId(cls, shotel_id): try: socket = TSocket.TSocket(cls.__host, cls.__port) transport = TTransport.TFramedTransport(socket) protocol = TCompactProtocol.TCompactProtocol(transport) client = MySqlQueryService.Client(protocol) transport.open() dValue = DataValue() dValue.data_type = 8 dValue.data_value = shotel_id shard_id = client.GetPartitionID(cls.__dbname, cls.__keyname, dValue) except Exception, ex: print Exception, ':', ex
def __init__(self, thrift_host, thrift_port, timeout=None, unix_socket=None): self._transObj = _Transport(thrift_host, thrift_port, timeout=timeout, unix_socket=unix_socket) self._protocol = TCompactProtocol.TCompactProtocol( trans=self._transObj.get_transport()) self.client = ThriftSourceProtocol.Client(iprot=self._protocol, oprot=self._protocol) self._transObj.connect()
def qrLogin(): Headers.update({'x-lpqs' : '/api/v4/TalkService.do'}) transport = THttpClient.THttpClient('https://gd2.line.naver.jp/api/v4/TalkService.do') transport.setCustomHeaders(Headers) protocol = TCompactProtocol.TCompactProtocol(transport) client = LineService.Client(protocol) qr = client.getAuthQrcode(keepLoggedIn=1, systemName=nama) link = "line://au/q/" + qr.verifier print(link) Headers.update({"x-lpqs" : '/api/v4/TalkService.do', 'X-Line-Access': qr.verifier}) json.loads(requests.session().get('https://gd2.line.naver.jp/Q', headers=Headers).text) Headers.update({'x-lpqs' : '/api/v4p/rs'}) transport = THttpClient.THttpClient('https://gd2.line.naver.jp/api/v4p/rs') transport.setCustomHeaders(Headers) protocol = TCompactProtocol.TCompactProtocol(transport) client = LineService.Client(protocol) req = LoginRequest() req.type = 1 req.verifier = qr.verifier req.e2eeVersion = 1 res = client.loginZ(req) print('\n') print(res.authToken)
def __init__(self, authToken): self.transport = THttpClient.THttpClient("https://" + self.host, None, self.http_query_path) self.transport.path = self.auth_query_path self.transport.setCustomHeaders({ "X-Line-Application": self.LA, "User-Agent": self.UA, "X-Line-Access": authToken }) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = LineService.Client(self.protocol) self.rev = self.client.getLastOpRevision() self.transport.path = self.polling_path self.transport.open()
def __init__( self, host_name, port, max_packet_size=UDP_PACKET_MAX_LENGTH, client=agent.Client, split_oversized_batches=False, ): self.address = (host_name, port) self.max_packet_size = max_packet_size self.buffer = TTransport.TMemoryBuffer() self.client = client(iprot=TCompactProtocol.TCompactProtocol( trans=self.buffer)) self.split_oversized_batches = split_oversized_batches
def createTransport(path=None, update_headers=None, service=None): Headers = { 'User-Agent': UA, 'X-Line-Application': LA, "x-lal": "ja-US_US", } Headers.update({"x-lpqs" : path}) if(update_headers is not None): Headers.update(update_headers) transport = THttpClient.THttpClient(host + path) transport.setCustomHeaders(Headers) protocol = TCompactProtocol.TCompactProtocol(transport) client = service(protocol) return client
def login(self): self.transport = THttpClient.THttpClient(self.host + ":" + str(self.port) + self.http_query_path) self.transport.setCustomHeaders(self.headers) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = LineService.Client(self.protocol) self.transport.open() self.transport.path = self.auth_query_path r = self.client.getRSAKeyInfo(IdentityProvider.LINE) data = (chr(len(r.sessionKey)) + r.sessionKey + chr(len(self.userid)) + self.userid + chr(len(self.password)) + self.password) pub = rsa.PublicKey(int(r.nvalue, 16), int(r.evalue, 16)) cipher = rsa.encrypt(data, pub).encode('hex') login_request = loginRequest() login_request.type = 0 login_request.identityProvider = IdentityProvider.LINE login_request.identifier = r.keynm login_request.password = cipher login_request.keepLoggedIn = 1 login_request.accessLocation = "127.0.0,1" login_request.systemName = self.pcname login_request.e2eeVersion = 1 self.transport.path = self.login_query_path r = self.client.loginZ(login_request) if r.type == LoginResultType.SUCCESS: self.setAttr(r.authToken, self.certificate) elif r.type == LoginResultType.REQUIRE_QRCODE: pass elif r.type == LoginResultType.REQUIRE_DEVICE_CONFIRM: print("Masukin kodenya mamank : {}".format(r.pinCode)) verifier = \ requests.get(url=self.host + self.wait_for_mobile_path, headers={"X-Line-Access": r.verifier}).json()["result"]["verifier"].encode("utf-8") verifier_request = loginRequest() verifier_request.type = 1 verifier_request.verifier = verifier verifier_request.e2eeVersion = 1 r = self.client.loginZ(verifier_request) self.uke('%s,%s' % (r.certificate, r.authToken)) else: print("Eror {}".format(r.type))
def open(self, enable_rpc_compression): if not self.__is_close: return self.__transport = TTransport.TFramedTransport( TSocket.TSocket(self.__host, self.__port)) if not self.__transport.isOpen(): try: self.__transport.open() except TTransport.TTransportException as e: print('TTransportException: ', e) if enable_rpc_compression: self.__client = Client( TCompactProtocol.TCompactProtocol(self.__transport)) else: self.__client = Client( TBinaryProtocol.TBinaryProtocol(self.__transport)) open_req = TSOpenSessionReq(client_protocol=self.protocol_version, username=self.__user, password=self.__password) try: open_resp = self.__client.openSession(open_req) if self.protocol_version != open_resp.serverProtocolVersion: print( "Protocol differ, Client version is {}, but Server version is {}" .format(self.protocol_version, open_resp.serverProtocolVersion)) # version is less than 0.10 if open_resp.serverProtocolVersion == 0: raise TTransport.TException( message="Protocol not supported.") self.__session_id = open_resp.sessionId self.__statement_id = self.__client.requestStatementId( self.__session_id) except Exception as e: self.__transport.close() print("session closed because: ", e) if self.__zone_id is not None: self.set_time_zone(self.__zone_id) else: self.__zone_id = self.get_time_zone() self.__is_close = False
def encode_and_decode(self, obj): trans = TMemoryBuffer() if self.PROTO == 0: proto = TBinaryProtocol.TBinaryProtocol(trans) else: proto = TCompactProtocol.TCompactProtocol(trans) obj.write(proto) obj_new = obj.__class__() trans = TMemoryBuffer(trans.getvalue()) proto = proto.__class__(trans) obj_new.read(proto)
def process(id, CI, CO): try: socket = TSocket.TSocket(HOST, PORT) transport = TTransport.TFramedTransport(socket) protocol = TCompactProtocol.TCompactProtocol(transport) client = Client(protocol) transport.open() req, req_v5 = build_req(id, CI, CO) req = build_message(id, CI, CO, 1) ret = client.SearchCanBook(req, req_v5) check_v(ret) transport.close() except Thrift.TException, tx: print "%s" % (tx.message)
def ready(self): """ After login, make `client` and `client_in` instance to communicate with LINE server """ """ After login, make `client` and `client_in` instance to communicate with LINE server """ self.transport = THttpClient.THttpClient(self.LINE_HTTP_URL) self.transport_in = THttpClient.THttpClient(self.LINE_HTTP_IN_URL) self.transport.setCustomHeaders(self._headers) self.transport_in.setCustomHeaders(self._headers) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.protocol_in = TCompactProtocol.TCompactProtocol(self.transport_in) self._client = CurveThrift.Client(self.protocol) self._client_in = CurveThrift.Client(self.protocol_in) self.transport.open() self.transport_in.open()
def __init__(self, authToken): self.authToken = authToken self.transport = THttpClient.THttpClient( 'https://gd2.line.naver.jp:443' + self.http_query_path) self.transport.setCustomHeaders({ "User-Agent": self.UA, "X-Line-Application": self.LA, "X-Line-Access": self.authToken }) self.transport.open() self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = LineService.Client(self.protocol) self.mid = self.client.getProfile().mid self.transport.path = self.channel_query_path
def createTransport(path=None, update_headers=None, service=None): Headers = { 'User-Agent': con.USER_AGENT, 'X-Line-Application': con.APP_NAME, "x-lal": "ja-US_US", } Headers.update({"x-lpqs": path}) if (update_headers is not None): Headers.update(update_headers) transport = THttpClient.THttpClient(con.LINE_HOST_DOMAIN + path) transport.setCustomHeaders(Headers) protocol = TCompactProtocol.TCompactProtocol(transport) client = service(protocol) return client
def se_thrift_compact(self): ''' Serialization using thrift compact protocol. ''' address_book = ttypes.AddressBook() address_book.person = [] start_time = time.clock() mem_buf = TTransport.TMemoryBuffer() bin_proto = TCompactProtocol.TCompactProtocol(mem_buf) for person in self._data_dic['input_data']['person']: one_person = ttypes.Person() one_person.name = person['name'] one_person.id = person['id'] if person['email'] != '': one_person.email = person['email'] one_person.phone = [] for phone in person['phone']: one_phone = ttypes.PhoneNumber() one_phone.number = phone['number'] if phone['type'] == '' or phone['type'] == 'HOME': one_phone.type = ttypes.PhoneType.HOME elif phone['type'] == 'MOBILE': one_phone.type = ttypes.PhoneType.MOBILE elif phone['type'] == 'WORK': one_phone.type = ttypes.PhoneType.WORK else: one_phone.type = ttypes.PhoneType.OTHER one_person.phone.append(one_phone) address_book.person.append(one_person) address_book.write(bin_proto) self._data_dic['seed_file_str'] = mem_buf.getvalue() end_time = time.clock() return end_time - start_time
def pythonServerExe(): try: transport = TSocket.TSocket( '192.168.40.10', 20001 ) transport = TTransport.TBufferedTransport( transport ) # protocol = TBinaryProtocol.TBinaryProtocol(transport) protocol = TCompactProtocol.TCompactProtocol( transport ) client = PythonService.Client( protocol ) transport.open() print "The return value is : " # print client.remove( 12 ) print client.helloString( "100" ) print "............" transport.close() except Thrift.TException, tx: print '%s' % ( tx.message )
def __init__(self, host="localhost", port=50096, user='******', password='******', _connect=True): super(Accumulo, self).__init__() self.transport = TTransport.TFramedTransport( TSocket.TSocket(host, port)) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = AccumuloProxy.Client(self.protocol) if _connect: self.transport.open() self.login = self.client.login(user, {'password': password})
def is_accelerated(): ''' Return whether this concrete-python installation has accelerated serialization. Returns: True if this concrete-python installation is accelerated, False otherwise ''' try: transport = TTransport.TMemoryBuffer() TCompactProtocol.TCompactProtocolAccelerated(transport, fallback=False) return True except Exception: return False
def start_server(self): print("Starting adapter server" + self.r_address.Address + ":" + str(self.r_address.Port)) processor = MMIAdapter.Processor( ThriftAdapterImplementation(self.session_data)) transport = TSocket.TServerSocket(host=self.a_address.Address, port=self.a_address.Port) tfactory = TTransport.TBufferedTransportFactory() pfactory = TCompactProtocol.TCompactProtocolFactory() #server = TServer.TThreadedServer(processor, transport, tfactory, pfactory) server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) server.setNumThreads(4) server.serve()
def _load_overlay_tree(overlay_dir: str, inode_number: int) -> OverlayDir: from thrift.util import Serializer from thrift.protocol import TCompactProtocol dir_name = '{:02x}'.format(inode_number % 256) overlay_file_path = os.path.join(overlay_dir, dir_name, str(inode_number)) with open(overlay_file_path, 'rb') as f: data = f.read() assert data[0:4] == b'OVDR' tree_data = OverlayDir() protocol_factory = TCompactProtocol.TCompactProtocolFactory() Serializer.deserialize(protocol_factory, data[64:], tree_data) return tree_data
def connect(self): """建立连接""" if isinstance(self.thrift_module, six.string_types): module = load_module(self.thrift_module) self.recorder('INFO', '{obj} connect start'.format(obj=self)) self._transport = TTornado.TTornadoStreamTransport( self.host, self.port) yield self._connect() self.recorder('INFO', '{obj} connect successful'.format(obj=self)) protocol = TCompactProtocol.TCompactProtocolFactory() self._client = getattr(module, 'Client')(self._transport, protocol) self.other = self._client raise Return(self)
def _create_client(self, address): host, port = address sock = TSocket.TSocket(host, port) sock.setTimeout(self._client_timeout) transport = TTransport.TFramedTransport(sock) protocol = TCompactProtocol.TCompactProtocol(transport) mp = TMultiplexedProtocol(protocol, self._service_name) client = self._client_class(mp) self._transports[client] = transport self._sockets[client] = sock transport.open() return client
def received_message(self, m): if not m.is_binary: #print "Non binary message" #print type(m) json_object = json.loads(str(m)) for element in json_object: #print element if json_object[element] == "error": continue if json_object[element] != "null" and json_object[ element] != "error": for bit in json_object[element]: try: if bit in self.infodict: #print "Value Exists" if self.infodict[bit] != json_object[element][ bit]: #queryupdate = "INSERT into messages (message,target,param1,complete) VALUES ('%s', 'details','%s','1')" % (bit,json_object[element][bit]) queryupdate = "UPDATE messages set param1 = '%s' where message = '%s'" % ( json_object[element][bit], bit) #print "Update Value" if args.verbose is True: print queryupdate self.infodict[bit] = json_object[element][ bit] cursor2.execute(queryupdate) db2.commit() #else: # print "Value Unchanged", else: #print element, bit, json_object[element][bit] self.infodict[bit] = json_object[element][bit] queryupdate = "INSERT into messages (message,target,param1,complete) VALUES ('%s', 'details','%s','1')" % ( bit, json_object[element][bit]) cursor2.execute(queryupdate) db2.commit() except: pass #print "d'oh" #else: # print "null" #print json_object #self.close() return transport = TTransport.TMemoryBuffer(m.data) protocol = TCompactProtocol.TCompactProtocol(transport) print "Binary Message"
def _login(self): """Login to LINE server.""" if self.provider == 1: # LINE j = self.get_json(self.LINE_SESSION_LINE_URL) else: # NAVER j = self.get_json(self.LINE_SESSION_NAVER_URL) session_key = j['session_key'] message = (chr(len(session_key)) + session_key + chr(len(self.id)) + self.id + chr(len(self.password)) + self.password).encode('utf-8') keyname, n, e = j['rsa_key'].split(",") pub_key = rsa.PublicKey(int(n, 16), int(e, 16)) crypto = rsa.encrypt(message, pub_key).encode('hex') self.transport = THttpClient.THttpClient(self.LINE_HTTP_URL) self.transport.setCustomHeaders(self._headers) self.protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = LineThrift.Client(self.protocol) print self.provider msg = self.client.loginWithIdentityCredentialForCertificate( self.id, self.password, False, self.ip, self.com_name, self.provider, crypto) self._headers['X-Line-Access'] = msg.verifier self._pinCode = msg.pinCode print "Enter PinCode '%s' to your mobile phone in 2 minutes"\ % self._pinCode j = self.get_json(self.LINE_CERTIFICATE_URL) self.verifier = j['result']['verifier'] msg = self.client.loginWithVerifierForCertificate(self.verifier) if msg.type == 1: self.certificate = msg.certificate self.authToken = self._headers['X-Line-Access'] = msg.authToken elif msg.type == 2: msg = "require QR code" self.raise_error(msg) else: msg = "require device confirm" self.raise_error(msg)
def __init__(self, settings): self.DB_URI = settings['HBASE_URI'] self.DB_PORT = settings['HBASE_PORT'] self.TB_INFO = settings['TB_INFO'].encode() self.TB_NEWS = settings['TB_NEWS'].encode() # 连接数据库表 socket = TSocket.TSocket(self.DB_URI, self.DB_PORT) self.transport = TTransport.TFramedTransport(socket) protocol = TCompactProtocol.TCompactProtocol(self.transport) self.client = THBaseService.Client(protocol) self.transport.open() # 将爬虫开始的信息存入数据库 self.spider_info_row_key, start_put = gen_start_spider_info() self.client.put(self.TB_INFO, start_put)
def encode_helper(self, obj): buf = fastproto.encode(obj, [obj.__class__, obj.thrift_spec, obj.isUnion()], utf8strings=0, protoid=self.PROTO) trans = TMemoryBuffer(buf) if self.PROTO == 0: proto = TBinaryProtocol.TBinaryProtocol(trans) else: proto = TCompactProtocol.TCompactProtocol(trans) obj_new = obj.__class__() obj_new.read(proto) self.assertEqual(obj, obj_new)
def login(host, port, name, password, appId, appGroupId): from thrift.transport import TTransport from thrift.transport import TSocket from thrift.protocol import TCompactProtocol from aclSystem import UserService try: logsocket = TSocket.TSocket(host, port) transport = TTransport.TFramedTransport(logsocket) protocol = TCompactProtocol.TCompactProtocol(transport) transport.open() global loginClient loginClient = UserService.Client(protocol) return loginClient.login(name, password, appId, appGroupId) except Exception: return None
def helperThreadConnect(self, userId): if userId in self.helper_authTokens: LINE_ACCESS_KEY = self.helper_authTokens.get(userId) else: return None helper_ConnectHeader = self.con_header.copy() helper_ConnectHeader["X-Line-Access"] = LINE_ACCESS_KEY transport = THttpClient.THttpClient(self.host + self.com_path) transport.setCustomHeaders(helper_ConnectHeader) protocol = TCompactProtocol.TCompactProtocol(transport) client = Client(protocol) transport.open() return client
class BinaryProtocol: '''thrift protocol''' def __init__(self,proto_type): self.proto_type = proto_type def thrift_proto(self, struct_object, data_dict, fun_name, mock_type): self.tran_str = TranStr.TranStr() print self.proto_type if self.proto_type == 1: self.protocol = TBinaryProtocol(self.tran_str) elif self.proto_type == 2: self.protocol = TCompactProtocol(self.tran_str) if mock_type == 2: self.protocol.writeMessageBegin(fun_name, TMessageType.CALL, 0) elif mock_type == 1: self.protocol.writeMessageBegin(fun_name, TMessageType.REPLY, 0) self.__tran_struct(struct_object, data_dict) self.protocol.writeMessageEnd() data_str = self.tran_str.get_protocol_str() data_str = struct.pack('!i',len(data_str)) + data_str return data_str def list_thrift_proto(self, struct_object, data_str, cur): self.un_tran_str = TranStr.UnTranStr(data_str,cur+4) if self.proto_type == 1: self.list_proto = TBinaryProtocol(self.un_tran_str) elif self.proto_type == 2: self.list_proto = TCompactProtocol(self.un_tran_str) data_dict = {} self.list_proto.readMessageBegin() data_dict = self.__un_tran_struct(struct_object) self.list_proto.readMessageEnd() return data_dict def __tran_struct(self, struct_object, data_dict): req_spec = struct_object() self.protocol.writeStructBegin(data_dict.keys()[0]) for i in range(len(req_spec.thrift_spec)): if req_spec.thrift_spec[i]==None: continue if req_spec.thrift_spec[i][2] in data_dict: #struct if req_spec.thrift_spec[i][1]==TType.STRUCT: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.STRUCT,i) self.__tran_struct(req_spec.thrift_spec[i][3][0],data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #string elif req_spec.thrift_spec[i][1]==TType.STRING: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.STRING,i) self.protocol.writeString(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #i32 elif req_spec.thrift_spec[i][1]==TType.I32: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.I32,i) self.protocol.writeI32(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #i16 elif req_spec.thrift_spec[i][1]==TType.I16: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.I16,i) self.protocol.writeI16(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #byte elif req_spec.thrift_spec[i][1]==TType.BYTE: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.BYTE,i) self.protocol.writeByte(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #i64 elif req_spec.thrift_spec[i][1]==TType.I64: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.I64,i) self.protocol.writeI64(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #bool elif req_spec.thrift_spec[i][1]==TType.BOOL: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.BOOL,i) self.protocol.writeBool(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #double elif req_spec.thrift_spec[i][1]==TType.DOUBLE: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.DOUBLE,i) self.protocol.writeDouble(data_dict[req_spec.thrift_spec[i][2]]) self.protocol.writeFieldEnd() #list elif req_spec.thrift_spec[i][1]==TType.LIST: self.protocol.writeFieldBegin(req_spec.thrift_spec[i][2],TType.LIST,i) self.protocol.writeListBegin(etype = req_spec.thrift_spec[i][3][0], size = len(data_dict[req_spec.thrift_spec[i][2]])) if req_spec.thrift_spec[i][3][0] == TType.STRUCT: self.__tran_list(data_dict[req_spec.thrift_spec[i][2]],req_spec.thrift_spec[i][3][0],req_spec.thrift_spec[i][3][1][0]) else: self.__tran_list(data_dict[req_spec.thrift_spec[i][2]],req_spec.thrift_spec[i][3][0]) self.protocol.writeListEnd() self.protocol.writeFieldEnd() self.protocol.writeFieldStop() self.protocol.writeStructEnd() def __un_tran_struct(self, struct_object): thrift_object = struct_object() data_dict = {} self.list_proto.readStructBegin() for i in range(len(thrift_object.thrift_spec)): if thrift_object.thrift_spec[i] == None: continue #i32 if thrift_object.thrift_spec[i][1] == TType.I32: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.list_proto.readI32() self.list_proto.readFieldEnd() #string elif thrift_object.thrift_spec[i][1] == TType.STRING: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.list_proto.readString() self.list_proto.readFieldEnd() #i64 elif thrift_object.thrift_spec[i][1] == TType.I64: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.list_proto.readI64() self.list_proto.readFieldEnd() #i16 elif thrift_object.thrift_spec[i][1] == TType.I16: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.list_proto.readI16() self.list_proto.readFieldEnd() #byte elif thrift_object.thrift_spec[i][1] == TType.BYTE: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.list_proto.readByte() self.list_proto.readFieldEnd() #bool elif thrift_object.thrift_spec[i][1] == TType.BOOL: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.list_proto.readBool() self.list_proto.readFieldEnd() #struct elif thrift_object.thrift_spec[i][1] == TType.STRUCT: self.list_proto.readFieldBegin() data_dict[thrift_object.thrift_spec[i][2]] = self.__un_tran_struct(thrift_object.thrift_spec[i][3][0]) self.list_proto.readFieldEnd() #list elif thrift_object.thrift_spec[i][1] == TType.LIST: self.list_proto.readFieldBegin() (etype,size) = self.list_proto.readListBegin() data_dict[thrift_object.thrift_spec[i][2]] = []#init list to dict if etype == TType.STRUCT: data_dict[thrift_object.thrift_spec[i][2]] = self.__un_tran_list(size, etype, thrift_object.thrift_spec[i][3][1][0]) else: data_dict[thrift_object.thrift_spec[i][2]] = self.__un_tran_list(size, etype) self.list_proto.readListEnd() self.list_proto.readFieldEnd() self.list_proto.readFieldBegin() self.list_proto.readStructEnd() return data_dict def __un_tran_list(self, list_len, list_type, *struct_object): data_list=[] for i in range(list_len): if list_type == TType.DOUBLE: list_proto_data = self.list_proto.readDouble() elif list_type == TType.I32: list_proto_data = self.list_proto.readI32() elif list_type == TType.I16: list_proto_data = self.list_proto.readI16() elif list_type == TType.I64: list_proto_data = self.list_proto.readI64() elif list_type == TType.BOOL: list_proto_data = self.list_proto.readBool() elif list_type == TType.STRING: list_proto_data = self.list_proto.readString() elif list_type == TType.BYTE: list_proto_data = self.list_proto.readByte() elif list_type == TType.STRUCT: list_proto_data = self.__un_tran_struct(struct_object[0]) data_list = data_list + [list_proto_data,] return data_list def __tran_list(self, data_list, list_type, *struct_object): for i in range(len(data_list)): if list_type == TType.STRUCT: self.__tran_struct(struct_object[0],data_list[i]) elif list_type == TType.I32: self.protocol.writeI32(data_list[i]) elif list_type == TType.I64: self.protocol.writeI64(data_list[i]) elif list_type == TType.BOOL: self.protocol.writeBool(data_list[i]) elif list_type == TType.DOUBLE: self.protocol.writeDouble(data_list[i]) elif list_type == TType.I16: self.protocol.writeI16(data_list[i]) elif list_type == TType.BYTE: self.protocol.writeByte(data_list[i]) elif list_type == TType.STRING: self.protocol.writeString(data_list[i])