def main(): URL = "http://rpc-server:80/" HEADERS = {'content-type': 'application/json'} payload = { "method": "echo", "params": ["echome!"], "jsonrpc": "2.0", "id": 0, } payload2 = { "method": "add", "params": [2, 3], "jsonrpc": "2.0", "id": 0, } # 1st client client = HTTPClient(URL) # 2nd client response = client.send(payload2) # response = requests.post(URL, data=json.dumps(payload2), headers=HEADERS).json() # 3rd client # response = request(URL, "echo", value="Yoko") print('RPC Response', response.data)
def main(context: click.core.Context, method: str, request_type: str, id: Any, send: str) -> None: """ Create a JSON-RPC request. """ exit_status = 0 # Extract the jsonrpc arguments positional = [a for a in context.args if "=" not in a] named = { a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a } # Create the request if request_type == "notify": req = Notification(method, *positional, **named) else: req = Request(method, *positional, request_id=id, **named) # type: ignore # Sending? if send: client = HTTPClient(send) try: response = client.send(req) except JsonRpcClientError as e: click.echo(str(e), err=True) exit_status = 1 else: click.echo(response.text) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
def __init__(self, cluster_url, username, api_key): """ Creates the Dotmesh client. """ self.cluster_url = cluster_url self.client = HTTPClient(cluster_url) self.client.session.auth = (username, api_key)
class Rpc: def __init__(self, node: str, devel=False): self.client = HTTPClient(node) self.account = Account(self.client) self.chain = Chain(self.client) self.engine = Engine(self.client) self.mempool = Mempool(self.client) self.net = Net(self.client) if devel: self.devel = Devel(self.client) def ping(self): payload = Request("ping") self.client.send(payload) def version(self): payload = Request("version") response = self.client.send(payload) return response.data.result def commit_hash(self): payload = Request("commitHash") response = self.client.send(payload) return response.data.result
def getMoneroBlockCount(url): client = HTTPClient(url) u = urlparse.urlparse(url) client.session.auth = HTTPDigestAuth(u.username, u.password) response = client.request('getblockcount') blocks = response.data.result['count'] return blocks
def __check_connection(self): url = "%s://%s:%s/jsonrpc" % (self.config.protocol, self.config.host, self.config.port) self.client = HTTPClient(url) self.client.session.auth = (self.config.username, self.config.passwd) response = self.client.send(Request('Application.GetProperties', list(), id_generator=id_generators.random())) if not response.data.ok: raise KodiServerCheckException()
def __init__(self, host='localhost', port=CC_DEFAULT_RPC_PORT, version="2.0", tls=False): self.version = version self.host = host self.port = port self.tls = tls scheme = 'http' if self.tls: scheme += 's' url = '{}://{}:{}'.format(scheme, self.host, self.port) self.http_client = HTTPClient(url)
def request(url: str, method: str, params: dict = None): if not params: params = {} client = HTTPClient(url) try: response = client.request(method, **params) except: raise else: return response.data.result
async def get_token_from_login_process(address, private_key): http_client = HTTPClient(CONFIG.http_uri + '/users') response = http_client.request(method_name='login_hash', address=address) random_result = json.loads(response.text)['result'] random_bytes = bytes.fromhex(random_result[2:]) signature_base64str = sign(private_key, random_bytes) response = http_client.request(method_name='login', address=address, signature=signature_base64str) token = json.loads(response.text)['result'] response = http_client.request(method_name='set_nickname', token=token, nickname=address) return token
def __init__(self, node: str, devel=False): self.client = HTTPClient(node) self.account = Account(self.client) self.chain = Chain(self.client) self.engine = Engine(self.client) self.mempool = Mempool(self.client) self.net = Net(self.client) if devel: self.devel = Devel(self.client)
def call_aiohttp(endpoint: str, **kwargs) -> Dict: try: client = HTTPClient(f'http://{endpoint}') r = client.request("_call", **kwargs) return {'status': SUCCEED_STATUS, 'data': r.data.result} except Exception as e: return { 'status': FAILED_STATUS, 'data': f'{str(e)}\n{traceback.format_exc()}' }
def _call_jsonrpc(self, target: str, method: RestMethod, params: Optional[NamedTuple], timeout): url = self._create_jsonrpc_url(target, method) http_client = HTTPClient(url) request = self._create_jsonrpc_params(method, params) response: Response = http_client.send(request, timeout=timeout) if isinstance(response.data, list): raise NotImplementedError( f"Received batch response. Data: {response.data}") else: return response.data.result
def message_sender(secondary_url, message, message_id, result_queue, retries_cnt): if retries_cnt <= retries: client = HTTPClient(secondary_url) print(len(message_id)) try: response = client.send(json.dumps(message)) print(json.loads(response.text)) message_id.append(response.data.id) result_queue.put(response.data.id) print(len(message_id)) except: print('exception') time.sleep(40) message_sender(secondary_url, message, message_id, result_queue, retries_cnt + 1) else: print('node ' + secondary_url + ' doesn''t work')
def get_client(login, token): """ Returns JSON RPC client """ client = HTTPClient('https://user-api.simplybook.me') client.session.headers.update({'X-Company-Login': login, 'X-Token': token}) return client
class ZilliqaAPI: """Json-RPC interface of Zilliqa APIs.""" class APIMethod: def __init__(self, api: "ZilliqaAPI", method_name: str): self.api = api self.method_name = method_name def __call__(self, *params, **kwargs): resp = self.api.call(self.method_name, *params, **kwargs) return resp and resp.data and resp.data.result def __init__(self, endpoint: str): self.endpoint = endpoint self.api_client = HTTPClient(self.endpoint) def __getattr__(self, item: str): return ZilliqaAPI.APIMethod(self, method_name=item) def call(self, method_name: str, *params, **kwargs): # fixme: fix for jsonrpcclient < 3.3.1 # if len(params) == 1 and (isinstance(params[0], (dict, list))): # params = (list(params), ) try: return self.api_client.request(method_name, *params, trim_log_values=True, **kwargs) except JsonRpcClientError as e: raise APIError(e)
def test_init_default_headers(self): client = HTTPClient("http://test/") # Default headers assert client.session.headers["Content-Type"] == "application/json" assert client.session.headers["Accept"] == "application/json" # Ensure the Requests default_headers are also there assert "Connection" in client.session.headers
def test(self): responses.add( responses.POST, "http://foo", status=200, body='{"jsonrpc": "2.0", "result": 5, "id": 1}', ) HTTPClient("http://foo").send_message(str(Request("foo")))
def hclient(remote_server, json_rpc): ''' sends a synchronous request to a remote RPC server ''' try: client = HTTPClient(remote_server) response = client.send(json_rpc) valstr = response.text val = json.loads(valstr) print("result: " + str(val["result"])) print("id: " + str(val["id"])) return valstr except Exception as err: logging.debug("node_client: " + str(err)) return '{"jsonrpc": "2.0", "result":"error", "id":"error"}'
def load_block_info(height_hash, fetch_size=True): block_data = dict() logging.getLogger('jsonrpcclient').setLevel(logging.ERROR) client = HTTPClient("http://127.0.0.1:20206/json_rpc") height_hash = str(height_hash) try: if len(height_hash) == 64: response = client.send(Request("getblock", hash=height_hash)).data.result else: height_hash = int(height_hash) response = client.send(Request("getblock", height=height_hash)).data.result except ReceivedNon2xxResponseError as e: logging.warning(e) return False, None block_data['block_hash'] = response['block_header']['hash'] block_data['block_difficulty'] = response['block_header']['difficulty'] block_data['timestamp'] = response['block_header']['timestamp'] block_data['time'] = datetime.utcfromtimestamp( block_data['timestamp']).strftime('%Y-%m-%d %H:%M:%S') block_data['height'] = response['block_header']['height'] block_data['topo_height'] = response['block_header']['topoheight'] block_data['depth'] = response['block_header']['depth'] block_data['tips'] = response['block_header']['tips'] json_data = json.loads(response['json']) block_data['miner_tx'] = json_data['miner_tx'] block_data[ 'miner_reward'] = response['block_header']['reward'] / 1000000000000 block_data['tx_hashes'] = json_data['tx_hashes'] block_data['size'] = 0 block_data['tx_size_list'] = list() if block_data['tx_hashes'] and fetch_size: block_data['tx_count'] = len(block_data['tx_hashes']) for tx in block_data['tx_hashes']: _, tx_data = load_tx_info(tx) block_data['size'] += tx_data['size'] block_data['tx_size_list'].append(tx_data['size']) block_data['size'] = "{0:.3f}".format(block_data['size']) block_data['hash_size_list'] = zip(block_data['tx_hashes'], block_data['tx_size_list']) else: block_data['tx_count'] = 0 return True, block_data
def test_init_custom_headers(self): client = HTTPClient("http://test/") client.session.headers["Content-Type"] = "application/json-rpc" # Header set by argument assert client.session.headers["Content-Type"] == "application/json-rpc" # Header set by DEFAULT_HEADERS assert client.session.headers["Accept"] == "application/json" # Header set by Requests default_headers assert "Connection" in client.session.headers
def __init__(self, url_or_client: Union[str, Client], methods: T): self.client: Client if isinstance(url_or_client, str): self.client = HTTPClient(url_or_client) else: self.client = url_or_client self.methods = self._original_methods = methods client_self = self class MethodsProxy: def __getattr__(self, method_name): return partial(client_self.request, method_name) # Replace self.methods with the proxy and hope that # static analysers don't notice setattr(self, "methods"[::-1][::-1], MethodsProxy())
def fetch_seat_availability(departure_station, arrival_station, departure_date, departure_time, train_number): client = HTTPClient(pico_paths.endpoint) """ store into into a payload to be sent out to endpoint """ request = Request( method="get_availability", channelId=pico_paths.channelId, train=train_number, origin=departure_station, destination=arrival_station, date=departure_date, time=departure_time, offer_codes=pico_paths.off_codes, ) """ send for a response """ seat_response = client.send(request=request, cert=pico_paths.cert_path, verify=False) request['method'] = "get_price" price_response = client.send(request=request, cert=pico_paths.cert_path, verify=False) merged_data = {} for service in seat_response.data.result: train_instance_data = {} for key, value in seat_response.data.result[service].items(): price = price_response.data.result.get(service) if price is None: train_instance_data.update({key: {"seats": value, "price": 0}}) else: train_instance_data.update({ key: { "seats": value, "price": price_response.data.result[service][key] } }) merged_data.update({service: train_instance_data}) return merged_data
def get_admin_client(self, login, token): """ Returns JSON RPC client for the admin interface """ admin_client = HTTPClient('https://user-api.simplybook.me/admin/') admin_client.session.headers.update({ 'X-Company-Login': login, 'X-User-Token': token }) return admin_client
def get_info(): logging.getLogger('jsonrpcclient').setLevel(logging.ERROR) client = HTTPClient("http://127.0.0.1:20206/json_rpc") network_data = dict() try: response = client.send(Request("get_info")).data.result network_data['difficulty'] = response['difficulty'] network_data['height'] = response['height'] network_data['topo_height'] = response['topoheight'] network_data['block_time'] = response['averageblocktime50'] network_data['total_supply'] = response['total_supply'] network_data['dynamic_fee_per_kb'] = response[ 'dynamic_fee_per_kb'] / 1000000000000 network_data['hash_rate'] = "{0:.3f}".format( float(network_data['difficulty']) / (12 * 1000000)) return network_data except ReceivedNon2xxResponseError as e: logging.warning(e)
def call(self, method, *args, **kwargs): provider = self.registry.get_random_provider(self.interface, version=self.version, group=self.group) # print service_url.location url = "http://{0}{1}".format(provider.location, provider.path) # print(url) client = HTTPClient(url) try: response = client.request(method, *args, **kwargs) if response.data.ok: return response.data.result else: raise DubboClientError(message=response.text, data=response.data) except HTTPError as e: raise ConnectionFail(None, e.filename) except ReceivedNon2xxResponseError as error: if error.code in dubbo_client_errors: message = str(error) raise dubbo_client_errors[error.code](message=message, data=error.args, code=error.code) else: message = str(error) raise DubboClientError(message=message, data=error.args, code=error.code) except ReceivedErrorResponseError as error: if error.response.code in dubbo_client_errors: message = str(error.response.message) raise dubbo_client_errors[error.response.code](message=message, data=error.response.data, code=error.response.code) else: message = str(error.response.message) raise DubboClientError(message=message, data=error.args, code=error.code) except JsonRpcClientError as error: raise DubboClientError(message=str(error), data=error.args) except Exception as ue: if hasattr(ue, 'message'): if hasattr(ue, 'reason'): raise InternalError(ue.message, ue.reason) else: raise InternalError(ue.message, None) else: raise InternalError(str(ue), None)
def send_end_game_request(game_room_id, addr1, addr2) -> str: data = { 'method': 'end_game', 'params': { 'game_id': game_room_id, 'addr1': addr1, 'addr2': addr2 } } params = CONFIG.icx_wallet.create_icx_origin_v3(data) print(f"params: {params}") response = HTTPClient(CONFIG.v3_uri).request('icx_sendTransaction', params) return json.loads(response.text)['result'] # tx_hash
def scrapeBlocks(): client = HTTPClient("http://node2.ticketszones.com:27093/json_rpc") blocks = [] height = 512582 p = 1 while height > 0: blocks += scrapePageOfBlocks(client, height) if p == 1: print(blocks[0]) stdout.write("\rscraped page %d" % p) stdout.flush() if p % 50 == 0: with open( baseDir + "/Data/OtherChains/tickets/historical_blocks.csv", "a") as dest: w = csv.DictWriter(dest, blocks[0].keys()) if p == 50: # if this is the first 50 pages, we'll need to write the headers to the csv file, then dump the data w.writeheader() w.writerows(blocks) with open(baseDir + "/Logs/tickets/blocks.txt", "a") as logfile: logfile.write("scraped page %d\n (height = %d" % (p, height)) blocks = [] p += 1 height -= 31 time.sleep(0.05) with open(baseDir + "/Data/OtherChains/tickets/historical_blocks.csv", "a") as dest: w = csv.DictWriter(dest, blocks[0].keys()) w.writerows(blocks) with open(baseDir + "/Logs/tickets/blocks.txt", "a") as logfile: logfile.write("%d pages of blocks scraped\n" % p)
def test_client(): url = "http://{0}{1}".format('172.19.3.111:38080/', 'com.ofpay.demo.api.UserProvider') client = HTTPClient(url) for x in range(number): response = client.request('getUser', 'A003') response2 = client.request( 'queryUser', { 'age': 18, 'time': 1428463514153, 'sex': 'MAN', 'id': 'A003', 'name': 'zhangsan' }) response3 = client.request('isLimit', 'MAN', 'Joe') response4 = client.request('getUser', 'A005')
def monitor(self, transform_id: Optional[str], refresh_time: float = 1.0): assert self.is_endpoint_set, 'Service endpoints are not set, please load config first' print('Starting aggregation monitor, waiting for Provider and Aggregator service...') r1 = rpc_client.call_aiohttp(self.provider_endpoint, call_id='ping')['status'] r2 = rpc_client.call(self.aggregator_endpoint, call_id='ping')['status'] while not (r1 and r2): time.sleep(0.1) r1 = rpc_client.call_aiohttp(self.provider_endpoint, call_id='ping')['status'] r2 = rpc_client.call(self.aggregator_endpoint, call_id='ping')['status'] provider_client = HTTPClient(f'http://{self.provider_endpoint}') zone_id = rpc_client.call_aiohttp(self.provider_endpoint, call_id='get_zone_id')['data'] stdscr = curses.initscr() curses.noecho() curses.cbreak() r = rpc_client.call(self.aggregator_endpoint, call_id='ls_all_transform_id') if r['status']: all_transforms = r['data'] else: curses.echo() curses.nocbreak() curses.endwin() print('Cannot query official transform IDs, exited console') return if not transform_id: self.monitor_all(zone_id, all_transforms, provider_client, stdscr, refresh_time) elif transform_id == 'stake_history' and transform_id in all_transforms: self.monitor_stake_history(zone_id, transform_id, provider_client, stdscr, refresh_time) elif transform_id in all_transforms: self.monitor_basic(zone_id, transform_id, provider_client, stdscr, refresh_time) else: curses.echo() curses.nocbreak() curses.endwin() print(f'Transform "{transform_id}" not found, exited console')
def scrapeBlocks(): client = HTTPClient("https://explorer.o3node.org/") blocks = [] start = 3282094 end = 3283093 p = 1851 while start > 0: blocks += scrapePageOfBlocks(client, start, end) if p == 1: print(blocks[0]) stdout.write("\rscraped page %d" % p) stdout.flush() if p % 50 == 0: with open(baseDir + "/Data/OtherChains/neo/historical_blocks.csv", "a") as dest: w = csv.DictWriter(dest, blocks[0].keys()) if p == 50: # if this is the first 50 pages, we'll need to write the headers to the csv file, then dump the data w.writeheader() w.writerows(blocks) with open(baseDir + "/Logs/neo/blocks.txt", "a") as logfile: logfile.write("scraped page %d\n ([start end] = [%d %d]" % (p,start,end)) blocks = [] p += 1 start -= 1000 end -= 1000 time.sleep(0.05) with open(baseDir + "/Data/OtherChains/neo/historical_blocks.csv", "a") as dest: w = csv.DictWriter(dest, blocks[0].keys()) w.writerows(blocks) with open(baseDir + "/Logs/neo/blocks.txt", "a") as logfile: logfile.write("%d pages of blocks scraped\n" % p)