async def process_request(self, request: JsonRpcRequest): try: print("< {0} {1}".format(request.request_id, request.method)) result = await app.call_procedure(request) response = JsonRpcResponse( request=request, result=result, ) await self.send_response(response) except error.JsonRpcError as rpc_error: response = JsonRpcResponse( request=request, error=rpc_error, ) await self.send_response(response) except Exception as e: print("Error", type(e), e.args) print(traceback.format_exc()) response = JsonRpcResponse( request=request, error=error.JsonRpcError(500, "Server internal error", str(e)), ) await self.send_response(response)
async def process_request(self, request: JsonRpcRequest): try: print("< {0} {1}".format(request.request_id, request.method)) result = await app.call_procedure(request) if isinstance(result, ResponseStream): self.__handle_response_stream(request, result) else: response = JsonRpcResponse( request=request, result=result, ) await self.send_response(response) except error.JsonRpcError as rpc_error: response = JsonRpcResponse( request=request, error=rpc_error, ) await self.send_response(response) except Exception as e: response = JsonRpcResponse( request=request, error=error.JsonRpcError(500, "Server internal error", str(e)), ) await self.send_response(response) raise e
async def __send_stream_response(self, request: JsonRpcRequest, data, last: bool): response = JsonRpcResponse( request=request, result=data, stream=not last, ) await self.send_response(response)
async def listen(self): while True: message = await self.websocket.recv() try: request = self.parse_request(message) except error.JsonRpcParseError as parse_error: response = JsonRpcResponse( request=None, error=parse_error, ) await self.send_response(response) else: await self.process_request(request)
async def listen(self): while True: message = await self.websocket.recv() try: request = self.parse_request(message) except error.JsonRpcParseError as parse_error: response = JsonRpcResponse( request=None, error=parse_error, ) await self.send_response(response) except ConnectionClosed: logging.info("Websocket connection closed.") else: await self.process_request(request)
async def send_response(self, response: JsonRpcResponse): data = response.to_json() print("Sending response") await self.websocket.send(data) print("> {}".format(data))