class ThriftClient(object): """ Thrift Client类封装。 """ def __init__(self, service, socket_config, service_name=None): trans_socket = TSocket(**socket_config) self.__transport = TBufferedTransportFactory()\ .get_transport(trans_socket) if service_name: protocol_factory = TMultiplexedProtocolFactory( TBinaryProtocolFactory(), service_name) else: protocol_factory = TBinaryProtocolFactory() protocol = protocol_factory.get_protocol(self.__transport) self.__client = TClient(service, protocol) self.__is_open = False def __del__(self): if self.__is_open: self.__transport.close() def __getattr__(self, item): if not self.__is_open: self.__transport.open() self.__is_open = True return getattr(self.__client, item)
def client(client_class=TTrackedClient, port=PORT): socket = TSocket("localhost", port) try: trans = TBufferedTransportFactory().get_transport(socket) proto = TBinaryProtocolFactory().get_protocol(trans) trans.open() args = [addressbook.AddressBookService, proto] if client_class.__name__ == TTrackedClient.__name__: args.insert(0, tracker) yield client_class(*args) finally: trans.close()
def client(client_class=TTrackedClient, port=6029): socket = TSocket("localhost", port) try: trans = TBufferedTransportFactory().get_transport(socket) proto = TBinaryProtocolFactory().get_protocol(trans) trans.open() args = [addressbook.AddressBookService, proto] if client_class.__name__ == TTrackedClient.__name__: args.insert(0, tracker) yield client_class(*args) finally: trans.close()
def init_client(self, ip, port): """Establish a connection to thrift server of ZLP Service. Init client opening sockets and init events handler. Args: ip (str): ipv6 network address of ZLP-Service port (str): port number on which ZLP-Service listens for requests """ client_socket = TSocket(ip, port, socket_family=socket.AF_INET, socket_timeout=50000) transport = TBufferedTransportFactory().get_transport(client_socket) protocol = TBinaryProtocolFactory().get_protocol(transport) transport.open() super().__init__(self.thrift_interface.ServiceInterface, protocol)