async def index(request): logger.debug('Stats page requested') settings = WebSettings() net_version = jsonrpcclient.request(settings.ETH_CLIENT, 'admin_nodeInfo') eth_client_modules = jsonrpcclient.request(settings.ETH_CLIENT, 'rpc_modules') shh_info = jsonrpcclient.request(settings.ETH_CLIENT, 'shh_info') accounts = jsonrpcclient.request(settings.ETH_CLIENT, 'personal_listAccounts') return { 'net_version': json.dumps(net_version, indent=4, sort_keys=True), 'eth_client_modules': json.dumps(eth_client_modules, indent=4, sort_keys=True), 'shh_info': json.dumps(shh_info, indent=4, sort_keys=True), 'accounts': json.dumps(accounts, indent=4, sort_keys=True), 'page_title': "Stats" }
def test_bipartite_graph(self): resp = jsonrpcclient.request( 'http://127.0.0.1:5000', 'bipartite_graph', { 'nodess': { "bipartite_0": [8, 7], "bipartite_1": [3, 4] }, "edges": [[3, 8], [4, 7]] }) self.assertEqual( resp, jsonify_response([False, 'nodes parameter is required', {}])) resp = jsonrpcclient.request( 'http://127.0.0.1:5000', 'bipartite_graph', { 'nodes': { "bipartite_0": [8, 7], "bipartite_1": [3, 4] }, "edgess": [[3, 8], [4, 7]] }) self.assertEqual( resp, jsonify_response([False, 'edges parameter is required', {}])) resp = jsonrpcclient.request( 'http://127.0.0.1:5000', 'bipartite_graph', { 'nodes': { "bipartitee_0": [8, 7], "bipartite_1": [3, 4] }, "edges": [[3, 8], [4, 7]] }) self.assertEqual( resp, jsonify_response([ False, 'Parameter bipartite_0 does not exist in given input', {} ])) resp = jsonrpcclient.request( 'http://127.0.0.1:5000', 'bipartite_graph', { 'nodes': { "bipartite_0": [8, 7], "bipartite_1": [3, 4] }, "edges": [[3, 8], [4, 7]] }) self.assertEqual( resp, jsonify_response([ True, 'success', { "bipartite_0": [8, 7], "bipartite_1": [3, 4], "edges": [[3, 8], [4, 7]] } ]))
def send_data(self, collection: str, data: dict): rpc_method = 'send_data' try: request(self.url, rpc_method, collection=collection, data=data) return True except ReceivedNon2xxResponseError: return False
def send_distributed_commands(self, command: list): rpc_method = 'send_distributed_commands' try: request(self.url, rpc_method, command=command) return True except ReceivedNon2xxResponseError as err: raise err return False
def start_notebook_server_in_thread(notebook_name: str, server, file_watcher_enabled: bool = False, status_widget=None): """ Args: notebook_name: The name of the notebook you want to be syncing in this process. file_watcher_enabled: If you're going to fire off events from a file watcher in your editor (like in PyCharm), then you don't need to enable this. It will just use the same HTTP requests as normal """ notebook_path = Path(notebook_name).absolute() if not status_widget: status_widget = widgets.Text() status_widget.style.description_width = "300px" display(status_widget) if file_watcher_enabled: assert False, "Currently unsupported." from watchdog.observers import Observer from jupyter_ascending.watchers.file_watcher import NotebookEventHandler event_handler = NotebookEventHandler(str(notebook_path.absolute()), file_watcher_enabled) file_observer = Observer() abs_path = str(notebook_path.parent.absolute()) file_observer.schedule(event_handler, abs_path, recursive=False) file_watcher_thread = threading.Thread(target=file_observer.start, args=tuple()) file_watcher_thread.start() # TODO: This might be a race condition if a bunch of these started at once... notebook_server_port = find_free_port() notebook_executor = HTTPServer( ("localhost", notebook_server_port), NotebookKernelRequestHandler, ) notebook_executor_thread = threading.Thread( target=notebook_executor.serve_forever, args=tuple()) notebook_executor_thread.start() J_LOGGER.info("IPYTHON: Registering notebook {}", notebook_path) request( EXECUTE_HOST_URL, server.register_notebook_server.__name__, # Params notebook_path=str(notebook_path), port_number=notebook_server_port, ) J_LOGGER.info("==> Success") make_comm() return status_widget
def perform_notebook_request(notebook_path: str, command_name: str, data: Dict[str, Any]) -> None: J_LOGGER.debug("Performing notebook request... ") notebook_server = get_server_for_notebook(notebook_path) if notebook_server is None: J_LOGGER.warning("==> Unable to process request") J_LOGGER.warning("==> {}", _REGISTERED_SERVERS) return request(notebook_server, command_name, data=data)
def request_notebook_command(json_request: GenericJsonRequest): try: request( EXECUTE_HOST_URL, perform_notebook_request.__name__, command_name=_map_json_request_to_function_name(json_request), notebook_path=json_request.file_name, data=attr.asdict(json_request), ) except ConnectionError as e: J_LOGGER.warning(f"Unable to connect to server. Perhaps notebook is not running? {e}") except ReceivedNon2xxResponseError as e: J_LOGGER.warning(f"Unable to process request. Perhaps something else is running on this port? {e}")
async def on_message(message): if message.author == client.user: return # Check if the address is on message if message.content: if message.channel.name in allowed_channels: message_words = message.content.split() for word in message_words: if re.search("^0x([A-Fa-f0-9]{40})$", word): url = 'https://cethswap.com/faucet/?user='******'&address=' + message.content r = requests.get(url) grantedCth = r.status_code == 200 # Using JSON-RPC to retrieve balance info from https://cheapeth.org/rpc blockNum = request("https://node.cheapeth.org/rpc", "eth_blockNumber").data.result bal = request("https://node.cheapeth.org/rpc", "eth_getBalance", word, blockNum).data.result count = request("https://node.cheapeth.org/rpc", "eth_getTransactionCount", word, blockNum).data.result bal = str(round(float.fromhex(bal) / (1e+18), 10)) count = str(int(count, 16)) print(bal) s = ('**' + message.author.name + '**' + ': ' + '<https://explore.cheapswap.io/account/' + word + '>' + '\n**Balance:** ' + bal + ' cTH' + '\n**Transactions**: ' + count) if (grantedCth): s += '\n**Faucet grants you 0.1 CTH: :droplet:**\n<https://cethswap.com/?cth_address=' + word + '&type=faucet>' cooldown = (datetime.datetime.now() + datetime.timedelta(seconds=60)) if allow_message(word, cooldown_list): cooldown_list.append((word, cooldown)) await message.channel.send(s) # Check if an attachment is on the message if message.content: if message.attachments: message_words = message.content.split() for word in message_words: if re.search("^[- a-fA-F0-9]{36}$", word): meme_time = (datetime.datetime.now() + datetime.timedelta(minutes=60)) meme_list.append([message, meme_time, word, 0])
def perform_notebook_request(notebook_path: str, command_name: str, data: Dict[str, Any]) -> Optional[Dict]: J_LOGGER.debug("Performing notebook request... ") try: notebook_server = get_server_for_notebook(notebook_path) except UnableToFindNotebookException: J_LOGGER.warning( f"Unabled to find {notebook_path} in {_REGISTERED_SERVERS}") return {"success": False, "notebook_path": notebook_path} request(notebook_server, command_name, data=data) return None
def get_token(self, login, api_key): """ Returns the token as per https://simplybook.me/en/api/developer-api/tab/guide_api """ token = request('https://user-api.simplybook.me/login/', 'getToken', login, api_key) return token.data.result
def get_key_authorization(self): rpc_method = 'is_authorized' try: req = request(self.url, rpc_method) return req.data.result except ReceivedNon2xxResponseError: return False
def test_emotion_rpc_call(): """test_emotion_rpc_call""" response = jsonrpcclient.request("http://127.0.0.1:{}".format(8001), "classify", image=IMAGE_64, image_type="jpg") assert response == EXPECTED_RESPONSE, "Is local jsonrpcserver running"
def get_info(self): rpc_method = "get_info" try: req = request(self.url, rpc_method) return req.data.result except (ReceivedNon2xxResponseError, ConnectionError): return False
def list_collections(self): rpc_method = 'get_collections' try: req = request(self.url, rpc_method) return req.data.result except ReceivedNon2xxResponseError: return False
def get_database_structure(self): rpc_method = 'get_database_structure' try: req = request(self.url, rpc_method) return req.data.result except ReceivedNon2xxResponseError: return False
def find_movie(self, pattern): androidtv = self.get_app("androidtv") androidtv.turn_on() androidtv.open_app("org.xbmc.kodi") response = request(URL, "VideoLibrary.GetMovies") movies = response.data.result.get("movies", None) def remove_extra_chars1(movie): label = re.sub("[-:]", "", movie.get("label")) return {**movie, "label": label} def remove_extra_chars2(movie): label = re.sub("-", " ", movie.get("label")) return {**movie, "label": label} if movies is None: return edited_movies1 = list(map(remove_extra_chars1, movies)) edited_movies2 = list(map(remove_extra_chars2, movies)) edited_movies = edited_movies1 + edited_movies2 + movies found = list( filter(lambda m: re.search(pattern, m.get("label"), re.IGNORECASE), edited_movies)) sorted_movies = list(sorted(found, key=lambda s: len(s.get("label")))) return sorted_movies
def get_user_token(company_login, user_login, user_password): """ Returns an authentication for a certain user, needed to create the admin client """ token = request('https://user-api.simplybook.me/login/', 'getUserToken', company_login, user_login, user_password) return token.data.result
def main(): script_name = sys.argv[0] parser = argparse.ArgumentParser(prog=script_name) server_name = "summary_server" default_endpoint = "http://127.0.0.1:{}".format( registry[server_name]['jsonrpc']) parser.add_argument("--endpoint", help="jsonrpc server to connect to", default=default_endpoint, type=str, required=False) parser.add_argument( "--snet", help="call service on SingularityNet - requires configured snet CLI", action='store_true') parser.add_argument("--source-text", help="path to txt file to summarise", type=str, required=True) args = parser.parse_args(sys.argv[1:]) endpoint = args.endpoint with open(args.source_text, 'r') as f: text = f.read() params = {'text': text} if args.snet: endpoint, job_address, job_signature = snet_setup( service_name="text_summarization", max_price=10000000) params['job_address'] = job_address params['job_signature'] = job_signature response = jsonrpcclient.request(endpoint, "summarise", **params) print(response)
def get_mission_list(self): rpc_method = "get_mission_list" try: req = request(self.url, rpc_method) mission_list = req.data.result return mission_list except ReceivedNon2xxResponseError: return False
async def test_bad_request(websocket: SolanaWsClientProtocol): """Test sending a malformed subscription request.""" bad_req = request("logsSubscribe", params=["foo"]) await websocket._send(bad_req) # pylint: disable=protected-access with pytest.raises(SubscriptionError) as exc_info: _ = await websocket.recv() assert exc_info.value.code == -32602 assert exc_info.value.subscription == bad_req
async def gimme(self, ctx: commands.Context, addr: str): if ctx.author.bot: return # Check if the address is on message if not ctx.message.content: return if ctx.channel.name in self.allowed_channels: message: discord.Message = ctx.message if re.search('^0x([A-Fa-f0-9]{40})$', addr): url = f'{self.faucet_url}{message.author.id}&address={addr}' r = requests.get(url) grantedCth = r.status_code == 200 print(r.status_code) # Using JSON-RPC to retrieve balance info from https://cheapeth.org/rpc blockNum = request(config.rpc_url, 'eth_blockNumber').data.result bal = request(config.rpc_url, 'eth_getBalance', addr, blockNum).data.result count = request(config.rpc_url, 'eth_getTransactionCount', addr, blockNum).data.result bal = str(round(float.fromhex(bal) / (1e+18), 10)) count = str(int(count, 16)) print(bal) s = f'**{message.author.name}**: <https://explore.cheapswap.io/account/{addr}>' s += f'\n**Balance**: {bal} cTH' s += f'\n**Transactions**: {count}' if grantedCth: s += f'\n**Faucet grants you 0.1 cTH: :droplet:**' s += f'\n<https://cethswap.com/?cth_address={addr}&type=faucet>' else: s += f'\n**You have not been given any cTH. Try again later.**' cooldown = datetime.datetime.now() + datetime.timedelta( seconds=60) if self.not_on_cooldown(addr): self.cooldowns[addr] = cooldown await message.channel.send(s)
def test_1(): import jsonrpcclient resp = jsonrpcclient.request('http://127.0.0.1:5000','bipartite_graph',{'nodes':{"bipartite_0": [8, 7], "bipartite_1": [3, 4]},"edges": [[3, 8], [4, 7]]}) # resp = jsonrpcclient.request('http://159.69.56.49:35000','bipartite_graph',{'nodes':{"bipartite_0": [8, 7], "bipartite_1": [3, 4]},"edges": [[3, 8], [4, 7]]}) print(resp)
def get_work_rpc( shard: Optional[int], host: str = "localhost", jrpc_port: int = 38391 ) -> MiningWork: json_rpc_url = "http://{}:{}".format(host, jrpc_port) header_hash, height, diff = jsonrpcclient.request( json_rpc_url, "getWork", hex(shard) if shard is not None else None ) return MiningWork(bytes.fromhex(header_hash[2:]), int(height, 16), int(diff, 16))
def fetch_peers(ip, jrpc_port): json_rpc_url = "http://{}:{}".format(ip, jrpc_port) print("calling {}".format(json_rpc_url)) peers = jsonrpcclient.request(json_rpc_url, "getPeers") return [ "{}:{}".format(ipaddress.ip_address(int(p["ip"], 16)), int(p["port"], 16)) for p in peers["peers"] ]
async def main(): async with ClientSession() as session: async with session.post("http://localhost:5000", json=request("ping")) as response: parsed = parse(await response.json()) if isinstance(parsed, Ok): print(parsed.result) else: logging.error(parsed.message)
def change_key_authorization(self, api_key: str, superuser=False, authorizing=True): rpc_method = 'modify_authorization' try: request(self.url, rpc_method, api_key=api_key, superuser=superuser, authorizing=authorizing) if authorizing: print(f"$$$ API key is now authorized (SU={superuser})") else: print("$$$ API key is now deauthorized") return True except ReceivedNon2xxResponseError: return False
def execute() -> dict: """Returns node peers information. :returns: Node peers information. """ response = rpc_client.request(pycspr.CONNECTION.address_rpc, _API_ENDPOINT) return response.data.result
def get_url_and_return_height(self, public_block_explorer_url): """ This ripple testnset explorer endpoint uses jrpc. """ try: resp = jsonrpcclient.request(public_block_explorer_url, 'ledger_current') except Exception as e: return re.search(r'ledger_current_index\': (.*?)}}', e.message).group(1) return None
def get_data(self, collection, database=None): rpc_method = 'get_data' try: req = request(self.url, rpc_method, collection=collection, database=database) return req.data.result except ReceivedNon2xxResponseError: return False
def query(endpoint, *args): retry, resp = 0, None while retry <= 5: try: resp = jsonrpcclient.request(HOST + ":" + PORT, endpoint, *args) break except Exception: retry += 1 time.sleep(0.5) return resp