def list_running_jobs(self): sealing_jobs._metrics.clear() running_jobs = get_json(self.api, self.token, "WorkerJobs", []) worker_stats = get_json(self.api, self.token, "WorkerStats", []) for worker in running_jobs['result']: for job in running_jobs['result'][worker]: sector_number = job['Sector']['Number'] sector_task = job['Task'] sector_state = \ self.WORKER_JOBS_RUNWAIT_STATE[str(job['RunWait'])] sector_start_time = time.mktime\ (time.strptime(job['Start'][:19], '%Y-%m-%dT%H:%M:%S')) sector_from_worker = worker try: sector_from_worker_hostname = \ worker_stats["result"][worker]["Info"]["Hostname"] except: sector_from_worker_hostname = "unknown" sealing_jobs.labels( miner_id = self.miner_id(), sector_number = sector_number, sector_from_worker = sector_from_worker, sector_from_worker_hostname = sector_from_worker_hostname, sector_task = sector_task, sector_state = sector_state ).set(time.time() - sector_start_time)
def wallet_balance(self): wallet_balance_list._metrics.clear() wallet_list = get_json(self.api, self.token, 'WalletList', []) default_wallet = \ get_json(self.api, self.token, 'WalletDefaultAddress', []) for wallet_address in wallet_list['result']: wallet_balance = get_json( self.api, self.token, 'WalletBalance', [wallet_address] ) mpool_get_nonce = get_json( self.api, self.token, 'MpoolGetNonce', [wallet_address] ) state_lookup_id = get_json( self.api, self.token, 'StateLookupID', [wallet_address, []] ) if wallet_address == default_wallet['result']: is_default = 'true' else: is_default = 'false' wallet_balance_list.labels( wallet_address = wallet_address, is_default = is_default, nonce = mpool_get_nonce['result'], id_address = state_lookup_id['result'] ).set(int(wallet_balance["result"])/1e18)
def mpool_pending(self, local=False): message_pool_pending_local._metrics.clear() wallet_list = get_json(self.api, self.token, 'WalletList', []) mpool_pending_messages = get_json( self.api, self.token, 'MpoolPending', [[]] ) for message in mpool_pending_messages['result']: if local: if message['Message']['From'] in wallet_list['result']: message_pool_pending_local.labels( To = message['Message']['To'], From = message['Message']['From'], nonce = message['Message']['Nonce'], value = message['Message']['Value'], gas_limit = message['Message']['GasLimit'], gas_fee_cap = message['Message']['GasFeeCap'], gas_premium = message['Message']['GasPremium'], method = \ self.METHODS_MINER[message['Message']['Method']], params = message['Message']['Params'], cid = message['CID']['/'], local = True ).set(message['Message']['Version']) else: if message['Message']['From'] in wallet_list['result']: message_pool_pending_local.labels( To = message['Message']['To'], From = message['Message']['From'], nonce = message['Message']['Nonce'], value = message['Message']['Value'], gas_limit = message['Message']['GasLimit'], gas_fee_cap = message['Message']['GasFeeCap'], gas_premium = message['Message']['GasPremium'], method = \ self.METHODS_MINER[message['Message']['Method']], params = message['Message']['Params'], cid = message['CID']['/'], local = True ).set(message['Message']['Version']) else: message_pool_pending_local.labels( To = message['Message']['To'], From = message['Message']['From'], nonce = message['Message']['Nonce'], value = message['Message']['Value'], gas_limit = message['Message']['GasLimit'], gas_fee_cap = message['Message']['GasFeeCap'], gas_premium = message['Message']['GasPremium'], method = \ self.METHODS_MINER[message['Message']['Method']], params = message['Message']['Params'], cid = message['CID']['/'], local = False ).set(message['Message']['Version'])
def search_same_image(img_url: str, item_per_page: int = 50) -> list: start_url = assemble_url(img_url, 0, item_per_page=item_per_page) print("\nsearch start url -> " + start_url + "\n") first_page = get_json(start_url) total_num = first_page['extra']['totalNum'] page_num = math.ceil((total_num - 1) / item_per_page) data: list = first_page['data'] if total_num > item_per_page: for i in range(1, page_num): url = assemble_url(img_url, i, item_per_page=item_per_page) page = get_json(url) data.extend(page['data']) return data
def predict(): if request.method == 'POST': try: # Get data for prediction (Parse data as JSON) json_data = request.get_json() # Raise an Error if there are values not entered if not all(k in json_data for k in ["hp", "age", "km", "model"]): raise ValueError("Not enough data to make a prediction!") # Create a DataFrame from JSON df = pd.DataFrame.from_dict([json_data], orient='columns') # Create dummy variables and persist features df = pd.get_dummies(df).reindex(columns=features, fill_value=0) # Note that if a column name (value) in JSON is wrong, # The relevant column is filled with '0' # Predict the target prediction = list(model_rf.predict(df)) # Return the result in JSON format return jsonify({"prediction": prediction}) except: return jsonify({'trace': traceback.format_exc()}) else: print("Nothing posted!") return "Nothing posted!"
def net_scores(self): net_pubsub_scores._metrics.clear() scores = get_json(self.api, self.token, 'NetPubsubScores', []) for peer_score in scores['result']: net_pubsub_scores.labels( peer_id = peer_score['ID'] ).set(peer_score['Score']['Score'])
def news(self) -> dict: try: json_data = get_json(f'{self.baseUrl}/news') return json_data except Exception as e: print(e) return {}
def teams(self) -> List[Team]: try: if not self._teams: self._teams = [] json_data = get_json( f'{self.baseUrl}/teams?groups={self.conferenceID}&limit=1000' ) for team in helpers.get_nested_dict_value( dictionary=json_data, ordered_list_of_keys=[ 'sports', 0, 'leagues', 0, 'teams' ], default_value=[]): new_team = Team(team_id=helpers.get_nested_dict_value( dictionary=team, ordered_list_of_keys=['team', 'id']), data={ 'league': self.league, 'sport': self.sport, 'base_url': self.baseUrl, 'teamNickname': None }) self._teams.append(new_team) return self._teams except Exception as e: print(e) return []
def roster(self) -> dict: try: if not self._roster: json_data = get_json( f'{self.baseUrl}/teams/{self.teamID}/roster') roster = [] for group in json_data.get('athletes', []): dictionary = { 'position': group.get('position'), 'players': None } players = [] for this_player in group.get('items', []): new_player = Player( this_player.get('id'), { 'league': self.league, 'sport': self.sport, 'base_url': f'https://site.web.api.espn.com/apis/common/v3/sports/{self.sport}/{self.league}/athletes' }) players.append(new_player) dictionary['players'] = players roster.append(dictionary) self._roster = roster return self._roster except Exception as e: print(e) return {}
def requestID(summoner_name): type_api = 'na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/' api_key = '<API KEY HERE>' summoner_name = stringutil.space_formator(summoner_name) url = stringutil.url_setter(True, type_api, summoner_name, api_key) return request.get_json(url)["id"] #returning id from json dict
def change_plataforma(id): for dev in game: if dev['id'] == id: dev['plataforma'] = request.get_json().get('plataforma') return jsonify(dev), 200 return jsonify({'error': 'dev not found'}), 404
def rankings(self) -> dict: try: json_data = get_json(f'{self.baseUrl}/rankings') self._rankings = json_data return self._rankings except Exception as e: print(e) return {}
def webhook(): req = request.get_json(silent=True, force=True) res = AIResquest(req) or Weather(req) or Feedback( req) ## DEFINING WEBHOOK FOR FUNCTION res = json.dumps(res, indent=4) print("Request: " + json.dumps(req, indent=4)) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
def webhook(): req = request.get_json(silent=True, force=True) print(json.dumps(req, indent=4)) res = makeResponse(req) req = json.dumps(res, indent=4) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
def add_karma(): getform = request.get_json() username = getform['username'] user = User.query.filter_by(username=username).first() if user: user.karma += 1 db.session.commit() return jsonify(message='Added karma'), 202 else: return jsonify('Could not add karma'), 404
def sub_karma(): getform = request.get_json() username = getform['username'] user = User.query.filter_by(username=username).first() if user: user.karma -= 1 db.session.commit() return jsonify(message='Subtracted karma!'), 202 else: return jsonify('Could not subtract karma'), 404
def new_transaction(): values = request.get_json() required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'Missing values', 400 index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f'Transaction will be added to Block {index}'} return jsonify(response), 201
def update_email(): getform = request.get_json() username = getform['username'] usersemail = User.query.filter_by(username=username).first() if usersemail: usersemail.email = getform['email'] usersemail.createtime = get_time() db.session.commit() return jsonify(message='Email updated'), 202 else: return jsonify('This user does not exist'), 404
def new_transaction(): # 创建/transaction/new POST接口,可以给接口发送交易数据 values = request.get_json() # return jsonify(values) # check that the required field are in the POST'ed data required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'Missing values', 400 # create a new transaction index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f'Transaction will be added to Block{index}'} return jsonify(response), 201
def register_nodes(): values = request.get_json() nodes = values.get('nodes') if nodes is None: return 'Error: Please supply a valid list of nodes', 400 for node in nodes: blockchain.register_node(node) response = { 'message': 'New nodes have been added', 'total_nodes': list(blockchain.nodes), } return jsonify(response), 201
def containers_create(): """ Create container (from existing image using id or name) curl -X POST -H 'Content-Type: application/json' http://localhost:8080/containers -d '{"image": "my-app"}' curl -X POST -H 'Content-Type: application/json' http://localhost:8080/containers -d '{"image": "b14752a6590e"}' curl -X POST -H 'Content-Type: application/json' http://localhost:8080/containers -d '{"image": "b14752a6590e","publish":"8081:22"}' """ body = request.get_json(force=True) image = body['image'] args = ('run', '-d') id = docker(*(args + (image,)))[0:12] return Response(response='{"id": "%s"}' % id, mimetype="application/json")
def post(self): request_json = request.get_json() username = request_json['username'] password = request_json['password'] db = client.sla col = db.users match = re.match(pwd_validate, password) if(col.find_one({"username" : username})==None and match!=None): user_id=col.insert_one({"username" : username, "password" : password}) return(Response(status=201)) #Created return(Response(status=400)) #Bad request: password/username error
def register_nodes(): values = request.get_json() nodes = values.get('nodes') if nodes is NOne: return "Error: Please suplly a valid list ofnodes", 400 for node in nodes: blockchain.register_node(node) response = { 'menssage': New nodes have been added 'total_nodes': list (blockchain.nodes), }
def sectors_list_states(self, count): sectors_states_dict = {} with open('.sector_states.tmp.json', 'r', encoding='UTF-8') \ as json_file_handler: data = json.load(json_file_handler) if data['Version'] == 0: for sector_state in self.EXIST_SECOTR_STATE_LIST: sectors_state = get_json( self.api, self.token, "SectorsListInStates", [[sector_state]] ) if sectors_state['result'] != None: sectors_state_list_len = len(sectors_state['result']) sectors_states_dict[sector_state] = sectors_state_list_len self.SECTORS_STATES_VERSION += 1 sectors_states_dict_new = { 'Version': self.SECTORS_STATES_VERSION, 'result': sectors_states_dict } with open('.sector_states.tmp.json', 'w') as json_file_handler: json_file_handler.\ write(json.dumps(sectors_states_dict_new, indent = 4)) elif data['Version'] in range(1, count): with open('.sector_states.tmp.json', 'r') as json_file_handler: data = json.load(json_file_handler) sectors_states_dict = data['result'] self.SECTORS_STATES_VERSION += 1 sectors_states_dict_new = { 'Version': self.SECTORS_STATES_VERSION, 'result': sectors_states_dict } with open('.sector_states.tmp.json', 'w') as json_file_handler: json_file_handler.\ write(json.dumps(sectors_states_dict_new, indent = 4)) else: self.SECTORS_STATES_VERSION = 0 sectors_states_dict = { 'Version': self.SECTORS_STATES_VERSION } with open('.sector_states.tmp.json', 'w') as json_file_handler: json_file_handler.\ write(json.dumps(sectors_states_dict, indent = 4)) for key, value in sectors_states_dict.items(): sectors_states_count.labels( miner_id = self.miner_id(), state = key ).set(int(value))
def net_bandwidth(self): net_bandwidth_stats = \ get_json(self.api, self.token, 'NetBandwidthStats', []) net_bandwidth.labels( stats = 'TotalIn' ).set(net_bandwidth_stats['result']['TotalIn']) net_bandwidth.labels( stats = 'TotalOut' ).set(net_bandwidth_stats['result']['TotalOut']) net_bandwidth.labels( stats = 'RateIn' ).set(net_bandwidth_stats['result']['RateIn']) net_bandwidth.labels( stats = 'RateOut' ).set(net_bandwidth_stats['result']['RateOut'])
def containers_update(id): """ Update container attributes (support: state=running|stopped) curl -X PATCH -H 'Content-Type: application/json' http://localhost:8080/containers/b6cd8ea512c8 -d '{"state": "running"}' curl -X PATCH -H 'Content-Type: application/json' http://localhost:8080/containers/b6cd8ea512c8 -d '{"state": "stopped"}' """ body = request.get_json(force=True) try: state = body['state'] if state == 'running': docker('restart', id) except: pass resp = '{"id": "%s"}' % id return Response(response=resp, mimetype="application/json")
def net_peers_list(self): net_peers._metrics.clear() net_peers_list = get_json(self.api, self.token, 'NetPeers', []) for net_peer in net_peers_list['result']: net_peer_id = net_peer['ID'] for index, net_address in enumerate(net_peer['Addrs']): global_location = location.ip_location(net_address) net_peers.labels( id = net_peer_id, address = net_address, country_name = global_location['country_name'], city_name = global_location['city_name'], latitude = global_location['location_latitude'], longitude = global_location['location_longitude'] ).set(index+1)
def new_transaction(): values = request.get_json() # Checking if the required data is there or not required = ["sender","recipient","amount"] if not all(k in values for k in required): return "missing values", 400 index = blockchain.new_transaction(values["sender"], values["recipient", values["amount"]]) response = {"message": "Transaction is scheduled to be added to Block No. {index}"} return jsonify(response), 201
def webhook(): config_reader = ConfigReader() configuration = config_reader.read_config() client = MongoClient( "mongodb+srv://your_username:"******"MONGO_PASSWORD"] + "@cluster0-p5lkb.mongodb.net/dialogflow?retryWrites=true&w=majority") db = client.dialogflow req = request.get_json(silent=True, force=True) print("Request:") print(json.dumps(req, indent=4)) intent_check = req.get("queryResult").get("intent").get("displayName") if (intent_check == "AboutCorona" or intent_check == "CountryCases" or intent_check == "CovidMap" or intent_check == "CovidTest" or intent_check == "Fallback" or intent_check == "Goodbye" or intent_check == "Menu" or intent_check == "MyAreaCases" or intent_check == "MythBuster" or intent_check == "Precaution" or intent_check == "QuarantineTips" or intent_check == "StateCases" or intent_check == "Symptoms" or intent_check == "Welcome"): res = saveToDb(req, db) elif intent_check == "GetCountryName": res = getCountryName(req, db) elif intent_check == "GetStateName": res = getStateName(req, db) elif intent_check == "GetUserDetails": res = getUserDetails(req, db) elif intent_check == "GlobalCases": res = globalCases(req, db) elif intent_check == "IndiaCases": res = indiaCases(req, db) elif intent_check == "News": res = news(req, db) res = json.dumps(res, indent=4) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
def register_node(): values = request.get_json() nodes = values.get('nodes') if nodes is None: return "Error: invalid node list", 400 for node in nodes: blockchain.register_node(node) response = { 'message': 'New node added', 'total_nodes': list(blockchain.nodes), } return jsonify(response), 201