def total_coin_supply(self): coins = 0 for k, v in self.db.RangeIter('Q'): if k[0] == ord('Q'): value = json.loads(v.decode('utf-8'))['value'] coins = coins + value[1] return coins
def search_txhash(self, txhash): # txhash is unique due to nonce. err = { 'status': 'Error', 'error': 'txhash not found', 'method': 'txhash', 'parameter': txhash } for tx in self.chain.transaction_pool: if tx.txhash == txhash: logger.info('%s found in transaction pool..', txhash) tx_new = copy.deepcopy(tx) self.reformat_txn(tx_new) return json_print_telnet(tx_new) try: txn_metadata = self.chain.state.db.get(txhash) except: logger.info( '%s does not exist in memory pool or local blockchain..', txhash) return json_print_telnet(err) json_tx = json.loads(txn_metadata[0]) tx = Transaction().from_txdict(json_tx) tx.blocknumber = txn_metadata[1] tx.confirmations = self.chain.height() - tx.blocknumber tx.timestamp = txn_metadata[2] tx_new = copy.deepcopy(tx) self.reformat_txn(tx_new) logger.info('%s found in block %s', txhash, str(txn_metadata[1])) tx_new.status = 'ok' return json_print_telnet(tx_new)
def getNodeInfo(baseDir, nodeName): ledger = getLedger(baseDir, NodeInfoFile, storeHash=False, isLineNoKey=False) rec = ledger.get(nodeName) return json.loads(rec)
def test_request_given_server_returns_an_authorisation_error_then_the_request_should_be_retried( self, mock_fetch_token): mock_fetch_token.return_value = "validToken" json_response = '{"resp2": "resp2"}' self.adapter.register_uri('GET', 'mock://test.com', [{ 'text': 'resp1', 'status_code': 401 }, { 'text': json_response, 'status_code': 200 }]) http_executor = http.HttpExecutor(auth.AuthFactory.create( grant_client_id="client_id", grant_client_secret="client_secret", token_url='mock://token-url.com'), session=self.session_mock, backoff_strategy={ 'interval': 0, 'max_tries': 1 }) response = http_executor.request("GET", "mock://test.com") assert_that(response.data, equal_to(json.loads(json_response)))
def return_all_addresses(self): addresses = [] for k, v in self.db.RangeIter('Q'): if k[0] == ord('Q'): v = json.loads(v.decode())['value'] addresses.append([k, v[1]]) return addresses
def _comparison_reply(responses, req_obj): for json_resp in responses.values(): resp = json.loads(json_resp) assert resp["op"] == REPLY assert resp[f.RESULT.nm][f.IDENTIFIER.nm] == req_obj[f.IDENTIFIER.nm] assert resp[f.RESULT.nm][f.REQ_ID.nm] == req_obj[f.REQ_ID.nm] assert resp[f.RESULT.nm][ACTION] assert resp[f.RESULT.nm][TXN_TYPE] == POOL_RESTART
def from_json(json_block): """ Constructor a block from a json string :param json_block: a block serialized as a json string :return: A block """ tmp_block = Block() tmp_block.json_to_block(json.loads(json_block)) return tmp_block
def create_post(request, id): global GMAIL try: store = file.Storage('WikiBreach/gmail.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets( 'WikiBreach/client_secret.json', 'https://mail.google.com/') creds = tools.run_flow(flow, store) GMAIL = discovery.build('gmail', 'v1', http=creds.authorize(Http())) except errors.HttpError as error: print('An error occurred: %s' % error) try: message_body = GMAIL.users().messages().get( userId='*****@*****.**', id=id).execute() data = message_body['payload'] msg = data['parts'] part = msg[1] body = part['body'] dat = body['data'] msg_str = base64.urlsafe_b64decode(dat.encode('UTF-8')) soup = BeautifulSoup(msg_str, "lxml") d = str(soup.find_all("script")) m = [] m = d.split("type=\"application/json\">", 1) p = m[1].split("</script>]", 1) msg_json = str(p[0]) data2 = json.loads(msg_json) date = data2['entity']['subtitle'] dateArray = date.split("Latest: ") date = dateArray[1] date = parser.parse(date).strftime('%Y-%m-%d') keyword = str(data2['entity']['title']).split("Google Alert - ")[1] widgets = data2["cards"][0] widgets = widgets['widgets'][0] title = widgets['title'] description = widgets['description'] source_url = widgets['url'] return render( request, 'createPost.html', { 'title': title, 'date': date, 'keyword': keyword, 'description': description, 'sourcelink': source_url, 'message_id': id }) except errors.HttpError as error: print('An error occurred: %s' % error)
def test_request_given_server_returns_an_error_then_the_request_should_be_retried_configured_times_by_default( self): json_response = '{"resp2": "resp2"}' self.adapter.register_uri('GET', 'mock://test.com', [{ 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': 'resp1', 'status_code': 500 }, { 'text': json_response, 'status_code': 200 }]) http_executor = http.HttpExecutor(auth.AuthFactory.create( grant_client_id="client_id", grant_client_secret="client_secret"), session=self.session_mock, backoff_strategy={ 'interval': 0, 'max_tries': 11 }) response = http_executor.request("GET", "mock://test.com") assert_that(response.data, equal_to(json.loads(json_response)))
def parse_request_body(request): if request.POST: request_body = request.POST.dict() # request_body = self._convert_string_bools_to_bools(request_body) else: try: request_body = json.loads(request.body) except BaseException as e: try: request_body = QueryDict(request.body).dict() # request_body = self._convert_string_bools_to_bools(request_body) except BaseException as e: request_body = {} return request_body
def delete_object(): data = request.get_json(force=True) if data: processed_data = json.loads(data) virtual_object_data = processed_data["cells"] virtual_object_name = processed_data["name"] if virtual_object_data: vo = VirtualObject(virtual_object_data, virtual_object_name) if _virtual_environment.remove_virtual_object(vo): return Response(status=200) else: return Response(response="Virtual Object Not found.", status=409) else: return Response(status=400)
def add_object(): data = request.get_json(force=True) if data: processed_data = json.loads(data) virtual_object_data = processed_data["cells"] virtual_object_name = processed_data["name"] if virtual_object_data: vo = VirtualObject(virtual_object_data, virtual_object_name) try: _virtual_environment.add_virtual_object(vo) except ValueError as e: return Response(response=e, status=409) return Response(status=200) else: return Response(status=400)
def changeWallpaper( self ): # Change the wallpaper to the "Desktop" (the background of the personal assistant) api_key = 'DphBLmcEqXGTCgF3q2UiP6kfR2z40fLfRs4F_Imqq7E' url = 'https://api.unsplash.com/photos/random?client_id=' + api_key # Picture from unspalsh.com r = requests.get(url, params={"orientation": "landscape"}) # Want only landscape pictures #print(r) json_string = r.text parsed_json = json.loads(json_string) photo = parsed_json['urls']['full'] #print(photo) image = urllib.request.urlretrieve(photo) # Save to temp location #print(image[0]) image_path = image[0] self.wallpaper.setPixmap(QPixmap(image_path)) # Set wallpaper s.AIResponse('wallpaper changed successfully')
def git_push_hook(webhook_parser: WebHookDataParser, handler: IssueHandler): data = request.data if len(data) == 0: return make_response("", 200) event_request = json.loads(data) logger.info("Request {}".format(json.dumps(event_request))) try: ref = webhook_parser.parse(event_request) except ParseError: return make_response("", 200) search = re.search(TRACKED_BRANCH_REGEXP, ref.ref_id) if (ref.update_type == "UPDATE") and (search is not None) and (re.search( WHITE_LISTED_REPOS, ref.repo_name)): logger.info("Submit commit for processing") __git_pool__.submit(process_hook_data, ref, handler) else: logger.info("Either repo {} or branch {} is not tracked".format( ref.repo_name, ref.ref_id)) return make_response("", 200)
def post(self, request): # b'aid=8$aname=zhangsan' bytes_str = request.body # 'aid=8$aname=zhangsan' str1 = bytes_str.decode() actor_dict = json.loads(str1) # 将请求参数存入数据库 actor = Actor.objects.create(aname=actor_dict.get('aname'), age=actor_dict.get('age'), agender=actor_dict.get('agender'), birth_date=actor_dict.get('birth_date'), ) return JsonResponse({ 'aid': actor.aid, 'aname': actor.aname, 'age': actor.age, 'agender': actor.agender, 'birth_date': actor.birth_date, 'photo': actor.photo.url if actor.photo else "" }, status=201)
def put(self, request, pk): 'PUT /actors/<pk>/' try: actor = Actor.objects.get(sid=pk) except Actor.DoesNotExist: raise HttpResponse(status=404) actor.dict = json.loads(request.body) #省略put请求方式中的数据类型验证 actor.aname = actor.dict.get('aname') actor.age = actor.dict.get('age') actor.save() return JsonResponse({ 'aid': actor.aid, 'aname': actor.aname, 'age': actor.age, 'agender': actor.agender, 'birth_date': actor.birth_date, 'photo': actor.photo.url if actor.photo else '' })
def put(self, request, pk): """修改演员信息""" try: actor = Actor.objects.get(aid=pk) except Actor.DoesNotExist: return HttpResponse(status=404) bytes_str = request.body str1 = bytes_str.decode() actor_dict = json.loads(str1) actor.aname = actor_dict.get("aname") actor.age = actor_dict.get("age") actor.save() return JsonResponse({ 'aid': actor.aid, 'aname': actor.aname, 'age': actor.age, 'agender': actor.agender, 'birth_date': actor.birth_date, 'photo': actor.photo.url if actor.photo else "" })
from tinydb import TinyDB DNSCacheDB = TinyDB('DNSCacheDB.json') request = Query() soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.bind(('0.0.0.0', 6985)) soc.listen(1) while True: print('Waiting for client data...') client_soc, address = soc.accept() byteData = client_soc.recv(1024) if byteData == b'': continue byteData = json.loads(str(byteData, encoding='utf_8')) cached = DNSCacheDB.search((request.target == byteData['target']) & (request.type == byteData['type'])) if cached: print('Founded in cache.') cached = cached[0] if int(time.time()) - cached['time'] <= cached['ttl']: byteData['response'] = cached['result'] client_soc.send(bytes(json.dumps(byteData), encoding='utf_8')) client_soc.close() continue else: print('ttl is over!') DNSCacheDB.remove((request.target == byteData['target']) & (request.type == byteData['type'])) print('Requested from server')
def search_address(self, address): addr = {'transactions': []} txnhash_added = set() # FIXME: breaking encapsulation and accessing DB/cache directly from API if not self.state.state_address_used(address): addr['status'] = 'error' addr['error'] = 'Address not found' addr['parameter'] = address return json_print_telnet(addr) # FIXME: This is a duplicate of balance # FIXME: breaking encapsulation and accessing DB/cache directly from API nonce, balance, pubhash_list = self.state.state_get_address(address) addr['state'] = {} addr['state']['address'] = address addr['state']['balance'] = self.format_qrlamount(balance) addr['state']['nonce'] = nonce for s in self.state.stake_list_get(): if address == s[0]: addr['stake'] = {} addr['stake']['selector'] = s[2] # pubhashes used could be put here.. tmp_transactions = [] for tx in self.chain.transaction_pool: if tx.subtype not in (TX_SUBTYPE_TX, TX_SUBTYPE_COINBASE): continue if tx.txto == address or tx.txfrom == address: logger.info('%s found in transaction pool', address) tmp_txn = { 'subtype': Transaction.tx_id_to_name(tx.subtype), 'txhash': bin2hstr(tx.txhash), 'block': 'unconfirmed', 'amount': self.format_qrlamount(tx.amount), 'nonce': tx.nonce, 'ots_key': tx.ots_key, 'txto': tx.txto, 'txfrom': tx.txfrom, 'timestamp': 'unconfirmed' } if tx.subtype == TX_SUBTYPE_TX: tmp_txn['fee'] = self.format_qrlamount(tx.fee) tmp_transactions.append(tmp_txn) txnhash_added.add(tx.txhash) addr['transactions'] = tmp_transactions my_txn = [] try: my_txn = self.state.db.get('txn_' + address) except: pass for txn_hash in my_txn: txn_metadata = self.state.db.get(txn_hash) dict_txn_metadata = json.loads(txn_metadata[0]) if dict_txn_metadata['subtype'] == TX_SUBTYPE_TX: tx = SimpleTransaction().json_to_transaction(txn_metadata[0]) elif dict_txn_metadata['subtype'] == TX_SUBTYPE_COINBASE: tx = CoinBase().json_to_transaction(txn_metadata[0]) if (tx.txto == address or tx.txfrom == address) and tx.txhash not in txnhash_added: logger.info('%s found in block %s', address, str(txn_metadata[1])) tmp_txn = { 'subtype': Transaction.tx_id_to_name(tx.subtype), 'txhash': bin2hstr(tx.txhash), 'block': txn_metadata[1], 'timestamp': txn_metadata[2], 'amount': self.format_qrlamount(tx.amount), 'nonce': tx.nonce, 'ots_key': tx.ots_key, 'txto': tx.txto, 'txfrom': tx.txfrom } if tx.subtype == TX_SUBTYPE_TX: tmp_txn['fee'] = self.format_qrlamount(tx.fee) addr['transactions'].append(tmp_txn) txnhash_added.add(tx.txhash) if len(addr['transactions']) > 0: addr['state']['transactions'] = len(addr['transactions']) addr['status'] = 'ok' if addr == {'transactions': {}}: addr = { 'status': 'error', 'error': 'address not found', 'method': 'address', 'parameter': address } return json_print_telnet(addr)
def test_request_given_server_returns_an_token_expired_error_then_the_request_should_be_retried( self): """ Testing the use of an invalid token and how the client-sdk should automatically get a new token. There are two type of errors when a new token is automatically retrieved: getting the TokenExpiredError exception and getting a valid response from the service with a 401 and using the auth method of providing credentials. This unit test checks both types: the exception and the 401 status error. """ json_response = '{"resp2": "resp2"}' mock_response_401 = Mock() mock_response_401.is_redirect = False mock_response_401.status_code = 401 mock_response_401.json.return_value = { "statusCode": 401, "error": "Unauthorized", "message": "Invalid token", "attributes": { "error": "Invalid token" } } mock_response_401.return_value.text = '{"statusCode":401,"error":"Unauthorized","message":"Invalid token","attributes":{"error":"Invalid token"}}' mock_response_200 = Mock() mock_response_200.is_redirect = False mock_response_200.status_code = 200 mock_response_200.return_value.text = json_response mock_response_200.json.return_value = {"resp2": "resp2"} mock_auth = Mock() mock_session = Mock() mock_session.request.side_effect = [ error.TokenExpiredError('Token Expired'), mock_response_401, mock_response_200 ] http_executor = http.HttpExecutor(mock_auth, session=mock_session, backoff_strategy={ 'interval': 0, 'max_tries': 2 }) response = http_executor.request("GET", "mock://test.com") assert_that(response.data, equal_to(json.loads(json_response))) call_list = [ call('GET', 'mock://test.com', allow_redirects=False, data=None, headers={ 'User-Agent': mock.ANY, 'Content-Type': 'application/vnd.piksel+json', 'Accept': 'application/vnd.piksel+json', 'X-Correlation-ID': None }, params=None, timeout=240), call('GET', 'mock://test.com', allow_redirects=False, data=None, headers={ 'User-Agent': mock.ANY, 'Content-Type': 'application/vnd.piksel+json', 'Accept': 'application/vnd.piksel+json', 'X-Correlation-ID': None }, params=None, timeout=240), call('GET', 'mock://test.com', allow_redirects=False, data=None, headers={ 'User-Agent': mock.ANY, 'Content-Type': 'application/vnd.piksel+json', 'Accept': 'application/vnd.piksel+json', 'X-Correlation-ID': None }, params=None, timeout=240) ] assert_that(mock_session.request.call_count, is_(3)) mock_session.request.assert_has_calls(call_list) assert_that(mock_session.auth.update_token.call_count, is_(2))
def test_request_given_server_returns_an_error_then_the_request_should_be_retried( self): json_response = '{"resp2": "resp2"}' mock_response_500 = Mock() mock_response_500.is_redirect = False mock_response_500.status_code = 500 mock_response_500.json.return_value = {} mock_response_500.return_value.text = json_response mock_response_200 = Mock() mock_response_200.is_redirect = False mock_response_200.status_code = 200 mock_response_200.return_value.text = json_response mock_response_200.json.return_value = {"resp2": "resp2"} mock_auth = Mock() mock_session = Mock() mock_session.request.side_effect = [ error.TokenExpiredError('Token Expired'), mock_response_500, mock_response_200 ] http_executor = http.HttpExecutor(mock_auth, session=mock_session, backoff_strategy={ 'interval': 0, 'max_tries': 2 }) response = http_executor.request("GET", "mock://test.com") assert_that(response.data, equal_to(json.loads(json_response))) call_list = [ call('GET', 'mock://test.com', allow_redirects=False, data=None, headers={ 'User-Agent': mock.ANY, 'Content-Type': 'application/vnd.piksel+json', 'Accept': 'application/vnd.piksel+json', 'X-Correlation-ID': None }, params=None, timeout=240), call('GET', 'mock://test.com', allow_redirects=False, data=None, headers={ 'User-Agent': mock.ANY, 'Content-Type': 'application/vnd.piksel+json', 'Accept': 'application/vnd.piksel+json', 'X-Correlation-ID': None }, params=None, timeout=240), call('GET', 'mock://test.com', allow_redirects=False, data=None, headers={ 'User-Agent': mock.ANY, 'Content-Type': 'application/vnd.piksel+json', 'Accept': 'application/vnd.piksel+json', 'X-Correlation-ID': None }, params=None, timeout=240) ] assert_that(mock_session.request.call_count, is_(3)) mock_session.request.assert_has_calls(call_list) assert_that(mock_session.auth.update_token.call_count, is_(1))
def getNodeInfo(baseDir, nodeName): ledger = getLedger(baseDir, NodeInfoFile, storeHash=False, isLineNoKey=False) rec = ledger.get(nodeName) ledger.close() return json.loads(rec)
# --- Detection & Recognition of a Pig --------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------- if PIG_RECOGNITION: with open(SAMPLE_IMG, 'rb') as f: im_b64 = base64.b64encode(f.read()) # Post Image for detection payload_detection_post = { 'imageId': '123', 'imageType': 'jpg', 'image': im_b64 } response_detection = requests.post(URL_POST_JSON_IMAGE_DETECTION, data=payload_detection_post) print('response detection post: ' + str(json.loads(response_detection.text))) # Get Detection Information & Image with mask payload_detection_get = {'imageId': '123', 'imageType': 'jpg'} response_detection = requests.get(URL_GET_JSON_IMAGE_DETECTION, data=payload_detection_get) print('response detection get: ' + str(json.loads(response_detection.text))) # Get Recognition Result Information # Example {'imageId': 'DSC_V2_6446_2774.JPG-crop-mask0.jpg', 'pig_name': '6446', 'accuracy': '0.9731434'} payload_recognition_get = {'imageId': '123', 'imageType': 'jpg'} response_recognition = requests.get(URL_GET_JSON_IMAGE_RECOGNITION, data=payload_recognition_get) print('response recognition get: ' + str(json.loads(response_recognition.text)))