def vkGetPosts(): data = json.loads(request.data) if 'type' not in data.keys(): return 'not vk' if (vkapi.check_server_key == False): return 'secret_key_is_wrong' if data['type'] == 'confirmation': return config.SERVER_COMFIRMATION_KEY else: write_json(data['object'], fileName="postFile") result = create_sendler_form(data['object']) result.Attachments = GetAttachments(data['object']) url = config.CSHARP_API_URL + "sendler/vkpost" headers = { 'Content-type': 'application/json', # Определение типа данных 'Accept': 'text/plain', 'Content-Encoding': 'utf-8' } if ((result is not None) and result != 400): write_json(data=result.__dict__, fileName="postresult") # write_json(data=jsons.dump(result.__dict__), fileName="postresult") response = opers.ExecuteActions(url=url, reqstType="POST", sending_body=jsons.dump( result.__dict__), headers=headers) if ("status_code" in response): send_error_message_to_developer(response) else: write_json(data=response, fileName="responseSendler") ApplySending(data=response, teleBot=teleBot, vkBot=vkapi.api) return 'ok' # if (response == "REQUEST_ERROR") return 'ok'
def test_dump_set(self): dat = datetime.datetime(year=2018, month=7, day=8, hour=21, minute=34, tzinfo=datetime.timezone.utc) set_ = {dat, dat} dumped = jsons.dump(set_) expected = ['2018-07-08T21:34:00Z'] self.assertEqual(dumped, expected)
def QuerySingleAction(name, event_tag=""): try: qs = Action.objects.filter(name=name) if qs: q = qs[0] questionInfo = [] for question in q.questions: qq = CalculatorQuestion(question, event_tag) # a question with no text is not to be included; this is how depending on the event_tag some questions would not be asked. if len(qq.questionText) > 0: questionInfo.append(jsons.dump(qq)) picture = "" if q.picture: picture = q.picture.file.url return VALID_QUERY, {"id": q.pk, "name":q.name, "title":q.title, "description":q.description, \ "category":q.category, "helptext":q.helptext, "questionInfo":questionInfo, \ "average_points":q.average_points, "picture":picture} else: print("ERROR: Action " + name + " was not found") return INVALID_QUERY, {} except: print("Failure to query action : " + name) return INVALID_QUERY, {}
def get_participant(self): for i in self.idplayer: json = db.get_player_by_id(i) play = players.deserialize(json) self.entrant.append(play) self.list_player_json.append(jsons.dump(play))
def suggestions(): query = request.args.get('q', default='', type=str) if len(query) < 1: return {'query': f'Query must be atleast 1 charectars - {query}'} # Search by ISBN number of a book, the title of a book, or the author of a book # SQL Wildcard - Anything that begins with # Lowers and handles other special language charectars query = query.casefold() query = f"{query}%" search_results = db.execute( """SELECT * FROM book WHERE isbn LIKE :query OR lower(title) LIKE :query OR lower(author) LIKE :query LIMIT 10""", {"query": query}) print(search_results.rowcount) books = [] for result in search_results: books.append( Book(result['isbn'], result['title'], result['author'], result['year'], result['created'])) print(result['isbn'], result['title'], result['author'], result['year']) json = {'query': request.args.get('q'), 'data': jsons.dump(books)} return json
def orderAccepted(self, order): log_print("Received notification of acceptance for: {}", order) # Log this activity. if self.log_orders: self.logEvent('ORDER_ACCEPTED', js.dump(order, strip_privates=True))
def index(): try: today = date.today() todayText = today.strftime("%d %B %Y").lstrip("0").replace(" 0", " ") months = { "January": "Ocak", "February": "Şubat", "March": "Mart", "April": "Nisan", "May": "Mayıs", "June": "HAziran", "July": "Temmuz", "August": "Ağustos", "September": "Eylül", "October": "Ekim", "November": "Kasım", "December": "Aralık" } searchQuery = todayText.replace(today.strftime("%B"), months[today.strftime("%B")]) day = request.args.get('day', str(searchQuery)) data = getEntries(day) container = EntryContainer(data, day) return render_template("index.html", data=jsons.dump(container)) except Exception as ex: raise Exception(ex)
def index(): """Return the homepage.""" """Return a list of data for today's games including our predictions for each game""" # Query all today games results = session.query(TodayPredictions).all() # Create a dictionary from the row data and append to a list of all_games today_games = [] for t_game in results: t_game_dict = {} t_game_dict["date"] = t_game.date t_game_dict["time"] = t_game.time t_game_dict["location"] = t_game.location t_game_dict["home_team"] = t_game.home_team t_game_dict["road_team"] = t_game.road_team t_game_dict["home_team_abr"] = t_game.home_team_abr t_game_dict["road_team_abr"] = t_game.road_team_abr t_game_dict["road_win_prediction"] = t_game.road_win_prediction t_game_dict["home_team_logo"] = t_game.home_team_logo t_game_dict["road_team_logo"] = t_game.road_team_logo today_games.append(t_game_dict) today_json = jsons.dump(today_games) print(today_json) return render_template("index.html", today_json=today_json)
def test_serialize_and_deserialize_with_case_transformer(self): class A: def __init__(self, snake_case_str, some_dict): self.snake_case_str = snake_case_str self.some_dict = some_dict class B: def __init__(self, a_obj: A, camel_case_str): self.a_obj = a_obj self.camel_case_str = camel_case_str b = B(A('one_two', {'some_key': 'some_value'}), 'theeFour') dumped_pascalcase = \ jsons.dump(b, key_transformer=jsons.KEY_TRANSFORMER_PASCALCASE) loaded_snakecase = \ jsons.load(dumped_pascalcase, B, key_transformer=jsons.KEY_TRANSFORMER_SNAKECASE) expected_dump = { 'AObj': { 'SnakeCaseStr': 'one_two', 'SomeDict': { 'SomeKey': 'some_value' } }, 'CamelCaseStr': 'theeFour' } self.assertEqual(expected_dump, dumped_pascalcase) self.assertEqual(loaded_snakecase.camel_case_str, 'theeFour') self.assertEqual(loaded_snakecase.a_obj.snake_case_str, 'one_two') self.assertEqual(loaded_snakecase.a_obj.some_dict['some_key'], 'some_value')
def poll(self, result_queue=None): r = {} vm = psutil.virtual_memory() r['state'] = "{:.1f}".format(vm.percent) r['attrs'] = jsons.dump(vm) self.polled_result = r return False
def poll(self, result_queue=None): r = {} disk = psutil.disk_usage(self.mountpoint) r['state'] = "{:.1f}".format(disk.percent) r['attrs'] = jsons.dump(disk) self.polled_result = r return False
def run(self): r = {} cpu_times = psutil.cpu_times_percent(interval=self.metric.interval, percpu=False) r['state'] = "{:.1f}".format(100.0 - cpu_times.idle) r['attrs'] = jsons.dump(cpu_times) self.metric.polled_result = r self.result_queue.put(self.metric)
def run(self): r = {} x = 0 interval = self.metric.interval tx_bytes = [] rx_bytes = [] prev_tx = 0; prev_rx = 0; base_tx = 0; base_rx = 0 while x < interval: nics = psutil.net_io_counters(pernic=True) if self.metric.nic in nics: tx = nics[self.metric.nic].bytes_sent rx = nics[self.metric.nic].bytes_recv if tx < prev_tx: # TX counter rollover base_tx += prev_tx if rx < prev_rx: # RX counter rollover base_rx += prev_rx tx_bytes.append(base_tx + tx) rx_bytes.append(base_rx + rx) prev_tx = tx prev_rx = rx time.sleep(1) x += 1 tx_rate_bytes_sec = average(diff(array(tx_bytes))) tx_rate = tx_rate_bytes_sec / 125.0 # bytes/sec to kilobits/sec rx_rate_bytes_sec = average(diff(array(rx_bytes))) rx_rate = rx_rate_bytes_sec / 125.0 # bytes/sec to kilobits/sec r['state'] = "{:.1f}".format(tx_rate + rx_rate) r['attrs'] = jsons.dump(nics[self.metric.nic]) r['attrs'].update({'tx_rate': float("{:.1f}".format(tx_rate)), 'rx_rate': float("{:.1f}".format(rx_rate))}) self.metric.polled_result = r self.result_queue.put(self.metric)
def cria_produto_com_tupla(tupla): return jsons.dump( Produto(id=tupla[0], nome=tupla[1], descricao=tupla[2], preco=tupla[3], contratacao=tupla[4]))
def test_load_object_verbose(self): class BarBase: pass class BarA(BarBase): def __init__(self, a: int): self.a = a class BarB(BarBase): def __init__(self, b: int): self.b = b class Foo(BarBase): def __init__(self, bar: BarBase): self.bar = bar jsons.announce_class(Foo) jsons.announce_class(BarA) jsons.announce_class(BarB) foo = Foo(bar=BarA(a=5)) dumped = jsons.dump(foo, verbose=True) loaded = jsons.load(dumped) self.assertTrue(isinstance(loaded, Foo)) self.assertTrue(isinstance(loaded.bar, BarA))
def test_dump_chain_map(self): d1 = {'a': 'A', 'b': 'B'} d2 = {'c': 'C', 'd': 'D'} m = ChainMap(d1, d2) dumped = jsons.dump(m) self.assertDictEqual({**d1, **d2}, dumped)
def test_dump_load_object_deep(self): class A: def __init__(self): self.name = 'A' class B: def __init__(self, list_a: List[A], list_dates: List[datetime.datetime]): self.list_a = list_a self.list_dates = list_dates self.name = 'B' class C: def __init__(self, list_b: List[B]): self.list_b = list_b c = C([B([A(), A()], []), B([], [datetime.datetime.now(), datetime.datetime.now()])]) dumped_c = jsons.dump(c) loaded_c = jsons.load(dumped_c, C) self.assertEqual(loaded_c.list_b[0].name, 'B') self.assertEqual(loaded_c.list_b[0].list_a[0].name, 'A') self.assertEqual(loaded_c.list_b[0].list_a[1].name, 'A') self.assertEqual(loaded_c.list_b[1].list_dates[0].year, c.list_b[1].list_dates[0].year) self.assertEqual(loaded_c.list_b[1].list_dates[0].month, c.list_b[1].list_dates[0].month) self.assertEqual(loaded_c.list_b[1].list_dates[0].day, c.list_b[1].list_dates[0].day) self.assertEqual(loaded_c.list_b[1].list_dates[0].hour, c.list_b[1].list_dates[0].hour) self.assertEqual(loaded_c.list_b[1].list_dates[0].minute, c.list_b[1].list_dates[0].minute) self.assertEqual(loaded_c.list_b[1].list_dates[0].second, c.list_b[1].list_dates[0].second)
def test_dump_as_parent_type_without_slots(self): class Parent: pass def __init__(self, pname): self.parent_name = pname class Child(Parent): def __init__(self, cname, pname): Parent.__init__(self, pname) self.child_name = cname c = Child('John', 'William') with self.assertRaises(SerializationError): jsons.dump(c, Parent)
def create_post_client_from_tele(message): client.BotChannel = "TELEGRAM" data = jsons.dump(client.__dict__) headers = { 'Content-type': 'application/json', # Определение типа данных 'Accept': 'text/plain', 'Content-Encoding': 'utf-8' } response_result = opers.ExecuteActions(url=config.CSHARP_API_BOT_URL + "createClient", reqstType='POST', headers=headers, sending_body=data) if (response_result == "REQUEST_ERROR"): server_error(message) send_error_message_to_developer(response_result) else: if ("status_code" in response_result): server_error(message) else: client.ClientBotId = response_result['clientBotId'] get_and_send_msg_text( message, "Регистрация прошла успешно! Подтвердите эл. почту, чтобы получать необходимую информацию и рассылку. Введите /help, чтобы получить больше инфорации." + "Ожидайте активации учётной записи администратором." if "TEACHER" in client.RoleCode else "")
def get_sp(): try: lin = linstor.Linstor(DEFAULT_LINSTOR_URI) lin.connect() # Fetch Storage Pool List sp_list_reply = jsons.dump(lin.storage_pool_list()[0].storage_pools) assert sp_list_reply, "Empty Storage Pool list" print(len(sp_list_reply)) sp_diskless_list = [] sp_list = [] node_count = 0 if sp_list_reply: for node in sp_list_reply: print(node["node_name"]) sp_node = {} sp_node['node_name'] = node["node_name"] sp_node['sp_uuid'] = node["uuid"] sp_node['sp_name'] = node["name"] if node["provider_kind"] == DISKLESS: diskless = True else: diskless = False # Driver selection if node["provider_kind"] == LVM: sp_node['driver_name'] = LVM elif node["provider_kind"] == LVM_THIN: sp_node['driver_name'] = LVM_THIN elif node["provider_kind"] == ZFS: sp_node['driver_name'] = ZFS elif node["provider_kind"] == ZFS_THIN: sp_node['driver_name'] = ZFS_THIN else: sp_node['driver_name'] = str(node["provider_kind"]) if diskless: sp_diskless_list.append(sp_node) else: sp_list.append(sp_node) node_count += 1 print(sp_node) # Add the diskless nodes to the end of the list if sp_diskless_list: sp_list.extend(sp_diskless_list) print('\nFound ' + str(len(sp_list)) + ' storage pools.') lin.disconnect() pprint.pprint(sp_list) return sp_list except Exception as e: print(str(e))
def _save_configuration(self): file_dir = self._get_configuration_directory() if not os.path.exists(file_dir): os.makedirs(file_dir) config_dict = jsons.dump(self.configuration) write_json_file_from_dict(data=config_dict, filename=f'{file_dir}/configuration.json')
def test_dump_object_strip_properties(self): obj = AllDumpable(AllDumpable()) exp = {'_par_c': 10, 'par_v': None, 'c': 1, '_c': 2, 'c_n': None, '_c_n': None, 'child': None, 'v': 3, '_v': 4, 'v_n': None, '_v_n': None} exp['child'] = exp.copy() dump = jsons.dump(obj, strip_properties=True) self.assertDictEqual(exp, dump)
def test_dump_object_strip_nulls(self): obj = AllDumpable(AllDumpable()) exp = {'_par_c': 10, 'par_p': 12, 'c': 1, '_c': 2, 'child': None, 'v': 3, '_v': 4, 'p': 5, '_p': 5} exp['child'] = exp.copy() exp['child'].pop('child') # child shouldn't have None child dump = jsons.dump(obj, strip_nulls=True) self.assertDictEqual(exp, dump)
def test_dump_object_strip_class_variables(self): obj = AllDumpable(AllDumpable()) exp = {'par_v': None, 'par_p': 12, 'child': None, 'v': 3, '_v': 4, 'v_n': None, '_v_n': None, 'p': 5, '_p': 5, 'p_n': None, '_p_n': None} exp['child'] = exp.copy() dump = jsons.dump(obj, strip_class_variables=True) self.assertDictEqual(exp, dump)
def test_dump_object_with_str_hint(self): class C: def __init__(self, x: 'str'): self.x = x dumped = jsons.dump(C('test'), cls=C) self.assertDictEqual({'x': 'test'}, dumped)
def test_dump_tuple_with_cls(self): t = (1, '2', 3, '4') dumped = jsons.dump(t, Tuple[int, str, int, int], strict=True) expected = [1, '2', 3, 4] # Note that the last element is an int. self.assertListEqual(expected, dumped)
def write_bookmarks(self): if not self._modified: return dir_path = _config_dir() native_dir_path = QDir.toNativeSeparators(dir_path) dir = QFileInfo(dir_path) if not dir.isDir(): print('Creating {}...'.format(native_dir_path)) if not QDir(dir.absolutePath()).mkpath(dir.fileName()): warnings.warn('Cannot create {}.'.format(native_dir_path), RuntimeWarning) return serialized_model = _serialize_model(self._model, dir_path) bookmark_file_name = os.path.join(native_dir_path, _bookmark_file) print('Writing {}...'.format(bookmark_file_name)) with open(bookmark_file_name, 'w') as bookmark_file: jsons.dump(serialized_model, bookmark_file, indent=4)
def post(self, request, *args, **kwargs): if len(request.body)<=2: return HttpResponse("<p>JSON body is empty!<p>", status=400) else: payload = json.loads(request.body) result = autocomplete(payload['slug']) json_to_send = jsons.dump(result) return Response(json_to_send)
def get(self, request, *args, **kwargs): if len(request.GET)<1: return HttpResponse("<p>Query is empty!<p>", status=400) else: name = request.GET['name'] result = get_product(name) json_to_send = jsons.dump(result) return Response(json_to_send)
def post(self, request, *args, **kwargs): if len(request.body)<=2: return HttpResponse("<p>JSON body is empty!<p>", status=400) else: payload = json.loads(request.body) result = get_kpi_insitu(payload) json_to_send = jsons.dump(result) return Response(json_to_send)