def authenticate(self): """ Performs authentication actions Patches `tinyrpc` to remove minor incompatibilities due to JSON-RPC protocol version differences. This is performed once. Initializes the RPCClient and RPCProxy instances that are used to make the requests to Lime. :return: None """ logger.info("Authenticating LimeAPI client") if not LimeAPI._rpc_protocol_patched: LimeAPI.patch_json_rpc_protocol() LimeAPI._rpc_protocol_patched = True self.rpc_client = RPCClient( JSONRPCProtocol(), HttpPostClientTransport(endpoint=self.remote_api_url, headers=self.headers), ) self.rpc_proxy = self.rpc_client.get_proxy() self.session_key = self.rpc_proxy.get_session_key( username=self.username, password=self.password) if not self._validate_session_key(): raise Exception(f"Failed to validate session key: url={self.url} " f"session_key={self.session_key}") self._authenticated = True logger.info(f"Acquired session key: {self.session_key}")
def login(self, username, password): self.rpc_client = RPCClient( JSONRPCProtocol(), HttpWebSocketClientTransport('ws://localhost:9001/api/ws')) self.loginManager = self.rpc_client.get_proxy("login.") hashed_password = hashlib.sha256(password).hexdigest() return self.loginManager.authenticate(username=username, password=hashed_password)
def worker(): ctx = zmq.Context() rpc_client = RPCClient( JSONRPCProtocol(), ZmqClientTransport.create(ctx, "tcp://127.0.0.1:5002")) proxy = rpc_client.get_proxy() for message in iter(partial(recv, port=sys.stdin), ""): proxy.post(f"hello {message}") import time time.sleep(0.4) sys.stdout.write("") sys.stdout.close()
def client(mock_protocol, mock_transport, request): client = RPCClient(mock_protocol, mock_transport, NoOpPublisher()) client.wait_for_task = Mock(return_value=None) response = Mock(RPCResponse) response.unicode = '0' response.result = 'result1' client.get_status = Mock(return_value={ response.unicode: ('done', response, 'some time', 'timeout') }) def fin(): client.receiver.alive = False request.addfinalizer(fin) return client
def manager(): cmd = [sys.executable, __file__, "worker"] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=False) rpc_client = RPCClient( JSONRPCProtocol(), SubprocessClientTransport(input_port=p.stdout, output_port=p.stdin), ) for i in range(3): proxy = rpc_client.get_proxy() try: result = proxy.add(10, 20) print(f"result is {result}") except Exception as e: logger.error("!! %r", e, exc_info=True) p.terminate()
def __init__(self, user, pwd): """Start RPC connection and keep session open Example: rpc = Satnet_RPC('crespum', 'solutions') print rpc.call('configuration.sc.list') :param user: SatNet username. :type user: L{String} :param pwd: SatNet password for this user. :type pwd: L{String} """ self._rpc_client = RPCClient(JSONRPCProtocolFix(), HttpSessionTransport(user, pwd)) self.detect_test(user) if self.testing: return if not self.login(user, pwd): raise BadCredentials() tw_log.msg('System login confirmed!')
def client(mock_protocol, mock_transport): return RPCClient(mock_protocol, mock_transport)
class CallbackServerTransport(ServerTransport): def receive_message(self) -> t.Tuple[t.Any, bytes]: context = "*context*" return context, in_box.pop(0) def send_reply(self, context: t.Any, reply: bytes): print(context) out_box.append(reply) rpc_server = RPCServer( CallbackServerTransport(), JSONRPCProtocol(), dispatcher, ) rpc_server.trace = print # 本来はこれを実行する # rpc_server.serve_forever() rpc_client = RPCClient(JSONRPCProtocol(), CallbackClientTransport()) proxy = rpc_client.get_proxy() try: result = proxy.add(10, 20) print(f"result is {result}") except Exception as e: print(e)
# def static_wsgi_app(environ, start_response): # start_response("200 OK", [("Content-Type", "text/html")]) # return open("assets/plot_graph.html").readlines() # # routes = [ # ('/', static_wsgi_app), # ('/data', PlotApplication) # ] if __name__ == "__main__": while not rpc_client: try: rpc_client = RPCClient( HttpWebSocketClientTransport('192.168.0.118:8000/buyer'), JSONRPCProtocol()) # TODO: check for reasonable exceptions except Exception, e: print e continue pm = PowerMeter(rpc_client) data = {'app': pm} pm_thread = gevent.spawn(pm.start) # resource = _Resource(routes, extra=data) # server = WebSocketServer(('', 8000), resource, debug=True) try: server.serve_forever() finally: pm.rpc_client.stop() GPIO.cleanup()