def timer(self, i): store = JsonStore('config.json') tmp_1 = self.count tmp_2 = time.gmtime(tmp_1) self.ids.count.text = time.strftime('%M:%S', tmp_2) for key, entry in store.find(active_questions=True): len_questions = store.get(key).get('number') if self.count == 0: self.pass_q += 1 self.ids.text_button.text = '{}/{}'.format(self.pass_q, len_questions) try: self.questions.pop(0) Clock.schedule_once(self.sound_play, 1) store = JsonStore('config.json') for key, entry in store.find(active_seconds=True): self.count = store.get(key).get('number') self.question = self.questions[0].get('name') # self.sound_play(self) except IndexError as err: print('IndexError: ', err) self.even_2.cancel() self.manager.current = 'done' self.count -= 1
def on_enter(self, *args): store = JsonStore('config.json') id_topic = self.ids.id_topic.text url = domain + '/app/detail/' + id_topic r = requests.get(url) try: r.raise_for_status() data = r.json() # get some random questions from JSON for key, entry in store.find(active_questions=True): count_questions = store.get(key).get('number') try: questions = random.sample(data, count_questions) except ValueError as err: questions = data TalkingScreen.questions = questions # pass Objects to TalkingScreen class i = 1 for x in questions: q = str(i) + '. ' + x.get('name') + ' ?' label = MDLabel(text=q) self.ids.box.add_widget(label) i += 1 btn = MDRaisedButton(text='Start', pos_hint={'center_x': 0.5}) self.ids.my_btn.add_widget(btn) btn.bind(on_press=self.go_to_talking) except requests.exceptions.HTTPError as err: print('Http error: ', err)
def on_enter(self, *args): self.name_topic = self.questions[0].get('topic').get('topic') Clock.schedule_once(self.sound_play, 1) store = JsonStore('config.json') self.ids.text_button.text = '{}/{}'.format(self.pass_q, len(self.questions)) for key, entry in store.find(active_seconds=True): self.count = store.get(key).get('number') self.question = self.questions[0].get('name') self.even_2 = Clock.schedule_interval(self.timer, 1) for key, entry in store.find(active_seconds=True): self.count = store.get(key).get('number') tmp_2 = time.gmtime(self.count) self.ids.count.text = time.strftime('%M:%S', tmp_2)
def on_leave(self, *args): self.even_2.cancel() store = JsonStore('config.json') for key, entry in store.find(active_seconds=True): tmp_1 = store.get(key).get('number') tmp_2 = time.gmtime(tmp_1) self.ids.count.text = time.strftime('%M:%S', tmp_2) self.count = tmp_1 self.pass_q = 1 self.ids.text_button.text = '{}/{}'.format(self.pass_q, len(self.questions))
from kivy.storage.jsonstore import JsonStore store = JsonStore('hello.json') # put some values store.put('tito', name='Mathieu', org='kivy') store.put('tshirtman', name='Gabriel', age=27) # using the same index key erases all previously added key-value pairs store.put('tito', name='Mathieu', age=30) # get a value using a index key and key print('tito is', store.get('tito')['age']) # or guess the key/entry for a part of the key for item in store.find(name='Gabriel'): print('tshirtmans index key is', item[0]) print('his key value pairs are', str(item[1])) # from kivy.storage.jsonstore import JsonStore # store = JsonStore('hello.json') # if store.exists('tito'): # print('tite exists:', store.get('tito')) # store.delete('tito')
import kivy from kivy.app import App from kivy.uix.label import Label from kivy.storage.jsonstore import JsonStore store = JsonStore('aluno.json') store.put('fulano', cpf='111', nome='Fulano', turma='INF28') for item in store.find(cpf='111'): x = '\nIndice: ' + item[0] + '\nChaves/Valores:\n' + str(item[1]) class MainApp(App): def build(self): return Label(text=x) MainApp().run()
class DataBase: url = 'https://ospapp-53708.firebaseio.com/.json?auth=' admin_passwd = '' def __init__(self, path, heroes_path, passwd_path): self.path = path self.store = JsonStore(path) with open("secret", 'r') as file: data = file.read().split("\n") self.url = self.url + data[0] self.firebase_patch_all() try: string = str(requests.get(self.url).json()['heroes']) if string: with open(heroes_path, 'w') as file: file.write(string) except Exception as e: print(str(e)) try: with open(heroes_path, 'r') as file: self.heroes = json.loads(str(file.read()).replace("'", '"')) except Exception as e: print(str(e)) self.heroes = ["brak strażaków w bazie"] try: string = str(requests.get(self.url).json()['passwd']) if string: with open(passwd_path, 'w') as file: file.write(string) except Exception as e: print(str(e)) try: with open(passwd_path, 'r') as file: global admin_passwd admin_passwd = file.readline() except Exception as e: print(str(e)) def put_report(self, uuid_num, id_number, dep_date, dep_time, spot_time, location, type_of_action, section_com, action_com, driver, perpetrator, victim, section, details, return_date, end_time, home_time, stan_licznika, km_location, completed): if uuid_num == "": uuid_num = str(uuid.uuid1()) if section_com == "Dowódca sekcji": section_com = "" if action_com == "Dowódca akcji": action_com = "" if driver == "Kierowca": driver = "" self.store.put(uuid_num, innerID=id_number, depDate=dep_date, depTime=dep_time, spotTime=spot_time, location=location, type=type_of_action, sectionCom=section_com, actionCom=action_com, driver=driver, perpetrator=perpetrator, victim=victim, section=section, details=details, returnDate=return_date, endTime=end_time, homeTime=home_time, stanLicznika=stan_licznika, KM=km_location, modDate=self.get_date(), ready=completed) try: string = "{'" + uuid_num + "': " + str( self.store.get(uuid_num)) + "}" to_database = json.loads(string.replace("'", '"')) requests.patch(url=self.url, json=to_database) except Exception as e: print(str(e)) def delete_report(self, uuid_num): if self.store.exists(uuid_num): try: # requests.delete(url=self.url[:-5] + id_number + ".json") string = '{"deleted-' + uuid_num + '": "true"}' to_database = json.loads(string) requests.patch(url=self.url, json=to_database) except Exception as e: Factory.deletePopout().open() print(str(e)) else: self.store.delete(uuid_num) else: return -1 def get_heroes(self): return self.heroes def firebase_patch_all(self): try: with open(self.path, 'r') as file: data = file.read() to_database = json.loads(data) requests.patch(url=self.url, json=to_database) except Exception as e: print(str(e)) def delete_all(self): string_all = "" try: for key in self.store.keys(): # requests.delete(url=self.url[:-5] + key + ".json") string = '{"deleted-' + key + '": "true"}' string_all = string_all + string to_database = json.loads(string) requests.patch(url=self.url, json=to_database) except Exception as e: Factory.deletePopout().open() print(str(e)) else: self.store.clear() def get_report(self, id_number): for item in self.store.find(innerID=id_number): dane = self.store.get(item[0]) id_number = dane['innerID'] dep_date = dane['depDate'] dep_time = dane['depTime'] spot_time = dane['spotTime'] location = dane['location'] type_of_action = dane['type'] section_com = dane['sectionCom'] action_com = dane['actionCom'] driver = dane['driver'] perpetrator = dane['perpetrator'] victim = dane['victim'] section = dane['section'] details = dane['details'] return_date = dane['returnDate'] end_time = dane['endTime'] home_time = dane['homeTime'] stan_licznika = dane['stanLicznika'] km_location = dane['KM'] date = dane['modDate'] completed = dane['ready'] return [ item[0], id_number, dep_date, dep_time, spot_time, location, type_of_action, section_com, action_com, driver, perpetrator, victim, section, details, return_date, end_time, home_time, stan_licznika, km_location, date, completed ] else: return -1 def get_all_friendly(self): result = [] for item in self.store.keys(): data = self.store.get(item) result.append(data["innerID"] + " " + data["location"]) return result def find_inner_id(self, id_number): for _ in self.store.find(innerID=id_number): return True return False @staticmethod def get_date(): return str(datetime.datetime.now()).split(".")[0] def get_passwd(self): global admin_passwd return admin_passwd
class DataBase: base_url = 'https://osptest-3ddc5.firebaseio.com/' url = '' secret = '' admin_password = '' def __init__(self, path, heroes_path, password_path, trucks_path, version): self.version = version self.heroes_path = heroes_path self.password_path = password_path self.trucks_path = trucks_path self.path = path self.store = JsonStore(path) with open("login_data/login", 'r') as file: self.user = file.read().split("\n")[0] with open("login_data/secret", 'r') as file: self.secret = file.read().split("\n")[0] self.url = self.base_url + self.user + self.secret self.firebase_patch_all() self.update_osp_data() def update_osp_data(self): try: string = str(requests.get(self.url).json()['heroes']) if string: with open(self.heroes_path, 'w') as file: file.write(string) except Exception as connection_error: Logger.exception(str(connection_error)) try: with open(self.heroes_path, 'r') as file: self.heroes = json.loads(str(file.read()).replace("'", '"')) except Exception as no_heroes_in_db: Logger.exception(str(no_heroes_in_db)) self.heroes = ["brak strażaków w bazie"] try: string = str(requests.get(self.url).json()['trucks']) if string: with open(self.trucks_path, 'w') as file: file.write(string) except Exception as connection_error: Logger.exception(str(connection_error)) try: with open(self.trucks_path, 'r') as file: self.trucks = json.loads(str(file.read()).replace("'", '"')) except Exception as no_trucks_in_db: Logger.exception(str(no_trucks_in_db)) self.trucks = ["brak zastepów w bazie"] try: string = str(requests.get(self.url).json()['passwd']) if string: with open(self.password_path, 'w') as file: file.write(string) except Exception as no_password_in_db: Logger.exception(str(no_password_in_db)) try: with open(self.password_path, 'r') as file: self.admin_password = file.readline() except Exception as no_password_file: Logger.exception(str(no_password_file)) def update_reports_data(self): result = self.firebase_patch_all() if result == -1: Factory.connectionPopout().open() else: self.update_osp_data() Factory.updateOK().open() def put_report(self, uuid_num, id_number, dep_date, dep_time, spot_time, location, type_of_action, section_com, action_com, driver, perpetrator, victim, section, details, return_date, end_time, home_time, meter_reading, km_location, completed, truck_num): if uuid_num == "": uuid_num = str(uuid.uuid1()) if section_com == "Dowódca sekcji": section_com = "" if action_com == "Dowódca akcji": action_com = "" if driver == "Kierowca": driver = "" if truck_num == "Zastęp": truck_num = "" self.store.put(uuid_num, innerID=id_number, depDate=dep_date, depTime=dep_time, spotTime=spot_time, location=location, type=type_of_action, sectionCom=section_com, actionCom=action_com, driver=driver, perpetrator=perpetrator, victim=victim, section=section, details=details, returnDate=return_date, endTime=end_time, homeTime=home_time, stanLicznika=meter_reading, KM=km_location, modDate=self.get_date(), ready=completed, truck=truck_num) try: string = "{'" + uuid_num + "': " + str( self.store.get(uuid_num)) + "}" to_database = json.loads(string.replace("'", '"')) requests.patch(url=self.url, json=to_database) return 0 except Exception as connection_error: Logger.exception(str(connection_error)) return -1 def delete_report(self, uuid_num): if self.store.exists(uuid_num): try: # requests.delete(url=self.url[:-5] + id_number + ".json") string = '{"deleted-' + uuid_num + '": "true"}' to_database = json.loads(string) requests.patch(url=self.url, json=to_database) self.store.delete(uuid_num) except Exception as connection_error: Factory.deletePopout().open() Logger.exception(str(connection_error)) else: return -1 def get_heroes(self): return self.heroes.get("all") def get_driver(self): return self.heroes.get("driver") def get_section_comm(self): return self.heroes.get("section") def get_action_comm(self): return self.heroes.get("action") def get_trucks(self): return self.trucks def firebase_patch_all(self): try: with open(self.path, 'r') as file: data = file.read() to_database = json.loads(data) requests.patch(url=self.url, json=to_database) to_database = json.loads('{"' + self.user + '": "' + self.version + '"}') requests.patch(url=self.base_url + "mobileVersion/" + self.secret, json=to_database) return 0 except Exception as connection_error: Logger.exception(str(connection_error)) return -1 def delete_all(self): string_all = "" try: for key in self.store.keys(): # requests.delete(url=self.url[:-5] + key + ".json") string = '{"deleted-' + key + '": "true"}' string_all = string_all + string to_database = json.loads(string) requests.patch(url=self.url, json=to_database) self.store.clear() except Exception as connection_error: Factory.deletePopout().open() Logger.exception(str(connection_error)) def get_report(self, id_number): for item in self.store.find(innerID=id_number): dane = self.store.get(item[0]) id_number = dane['innerID'] dep_date = dane['depDate'] dep_time = dane['depTime'] spot_time = dane['spotTime'] location = dane['location'] type_of_action = dane['type'] section_com = dane['sectionCom'] action_com = dane['actionCom'] driver = dane['driver'] perpetrator = dane['perpetrator'] victim = dane['victim'] section = dane['section'] details = dane['details'] return_date = dane['returnDate'] end_time = dane['endTime'] home_time = dane['homeTime'] meter_reading = dane['stanLicznika'] km_location = dane['KM'] date = dane['modDate'] completed = dane['ready'] truck_num = dane['truck'] return [ item[0], id_number, dep_date, dep_time, spot_time, location, type_of_action, section_com, action_com, driver, perpetrator, victim, section, details, return_date, end_time, home_time, meter_reading, km_location, date, completed, truck_num ] else: return -1 def get_all_friendly(self): result = [] for item in self.store.keys(): data = self.store.get(item) result.append(data["innerID"] + " " + data["location"]) return result def find_inner_id(self, id_number): for _ in self.store.find(innerID=id_number): return True return False @staticmethod def get_date(): return str(datetime.datetime.now()).split(".")[0] def get_user(self): return self.user def get_password(self): return self.admin_password def change_osp(self, user, password): with open("login_data/login", 'r') as file: old_user = file.read().split("\n")[0] if user != old_user: try: user_password = str( requests.get(self.base_url + "passwd/" + user + self.secret).json()) to_database = json.loads('{"' + user + '": "' + self.version + '"}') requests.patch(url=self.base_url + "mobileVersion/" + self.secret, json=to_database) except Exception as connection_error: Logger.exception(str(connection_error)) return -2 # no connection if user_password == "UPDATE": return -3 # update neeeded if user_password == "None" or password != user_password: return -1 # wrong password self.url = self.base_url + user + self.secret try: string = str(requests.get(self.url).json()['heroes']) with open(self.heroes_path, 'w') as file: file.write(string) except Exception as connection_error: Logger.exception(str(connection_error)) with open(self.heroes_path, 'w') as file: file.write("") try: with open(self.heroes_path, 'r') as file: self.heroes = json.loads( str(file.read()).replace("'", '"')) except Exception as no_heroes_in_db: Logger.exception(str(no_heroes_in_db)) self.heroes = ["brak strażaków w bazie"] try: string = str(requests.get(self.url).json()['trucks']) with open(self.trucks_path, 'w') as file: file.write(string) except Exception as connection_error: Logger.exception(str(connection_error)) try: with open(self.trucks_path, 'r') as file: self.trucks = json.loads( str(file.read()).replace("'", '"')) except Exception as no_trucks_in_db: Logger.exception(str(no_trucks_in_db)) self.trucks = ["brak zastepów w bazie"] try: string = str(requests.get(self.url).json()['passwd']) with open(self.password_path, 'w') as file: file.write(string) except Exception as connection_error: Logger.exception(str(connection_error)) self.url = self.base_url + self.user + self.secret return -2 try: with open(self.password_path, 'r') as file: self.admin_password = file.readline() except Exception as no_password: Logger.exception(str(no_password)) self.store.clear() self.user = user with open("login_data/login", 'w') as file: file.write(user) return 0
# subistituindo valor store.put('tito', name='Mathieu', age=30) # recuperando valor print('tito is', store.get('tito')['age']) # verificanco se existe if store.exists('tito'): print('tite exists:', store.get('tito')) # deletando valor store.delete('tito') # trz todas ocorrencia em que nome é igual Gabriel for item in store.find(name='Gabriel'): print('tshirtmans index key is', item[0]) print('his key value pairs are', str(item[1])) entries = list( store.find(name='Mathieu')) #pode ser usado convertido em uma lista store.clear() # Limpe todo o armazenamento. store.count() # Retorna o número de entradas armazenadas. store.keys() #Retorna uma lista com todas as chaves armazenadas. # ========================================================== # ASSINCRONA # se definir o callback a funcao torna se assincrona
class NameProvider(object): update_callback = None def __init__(self): self.name_store = None self.rating_store = None self.current_query = None self.cache = None self.index = 0 def get_rst(self, name, name_data): text = "**Sprache**\n\n %s\n\n" % name_data["language"] if name_data["meaning"] != "-": text += "**Bedeutung**\n\n %s \n\n" % name_data["meaning"] if name_data["origin"] != "-": text += "**Herkunft**\n\n %s\n\n" % name_data["origin"] if name_data["words"] != "-": text += u"**Wörter**\n\n %s\n\n" % name_data["words"] variants = [x for x in name_data["variants"] if x != name] if variants: text += "**Varianten**\n\n %s\n\n" % ', '.join(variants) return text def get_by_name(self, name): if not self.name_store: self.name_store = JsonStore("names.json") try: return name, self.name_store.get(name) except KeyError: pass return None def _update_cache(self, gender, starts_with, ends_with, min_len, max_len, langs): self.cache = [] self.index = 0 if not self.rating_store: self.rating_store = JsonStore("ratings.json") add_to_cache = self.cache.append gender_letter = gender[0] has_gender = gender_letter in ("m", "w") rating_store_exists = self.rating_store.exists min_len = int(min_len) max_len = int(max_len) if not self.name_store: self.name_store = JsonStore("names.json") if not self.rating_store: self.rating_store = JsonStore("ratings.json") for name, data in self.name_store.find(): try: if has_gender and not data["gender"].startswith(gender_letter): continue if data["length"] < min_len or data["length"] > max_len: continue if rating_store_exists(name): continue if langs[make_lang_key(data["language"])] != u'1': continue name_lc = name.lower() if starts_with != "" and not name_lc.startswith(starts_with): continue if ends_with != "" and not name_lc.endswith(ends_with): continue add_to_cache(name) except TypeError: pass except KeyError: pass def get_next_unrated_name(self, gender, starts_with, ends_with, min_len, max_len, langs): query = (gender, starts_with, ends_with, min_len, max_len, langs) if cmp(query, self.current_query) != 0: self._update_cache(*query) self.current_query = query if self.cache: #next_name = random.choice(self.cache) next_name = self.cache[self.index] self.index = (self.index + 1) % len(self.cache) return self.get_by_name(next_name), len(self.cache) return None, 0 def rate(self, current_name, rating): if not self.rating_store: self.rating_store = JsonStore("ratings.json") self.cache.remove(current_name[0]) self.rating_store.put(current_name[0], gender=current_name[1]["gender"], rating=rating) def change_rating(self, name, gender, rating): if not self.rating_store: self.rating_store = JsonStore("ratings.json") self.rating_store.put(name, gender=gender, rating=rating) def get_favorites(self): if not self.rating_store: self.rating_store = JsonStore("ratings.json") return sorted([(x, y["gender"]) for x, y in self.rating_store.find(rating=1)]) def delete_con_rating(self): if not self.rating_store: self.rating_store = JsonStore("ratings.json") cons = [x for x, _ in self.rating_store.find(rating=0)] for name in cons: self.rating_store.delete(name) self._update_cache(*self.current_query)
class JsonN(ScrollView): currentProjectPath = StringProperty('null') currentProjectName = StringProperty('null') def __init__(self, **kwargs): super(JsonN, self).__init__() # props assetsPath # inject path self.assetsPath = kwargs.get("assetsPath", "null") self.currentContainer = kwargs.get("currentContainer") self.engineRoot = kwargs.get("engineRoot") # Reset self.orientation = 'horizontal' self.cols = 1 self.size_hint = (1,1) self.pos_hint = {'center_x':0.5,'top': 1} self.selfUpdate() self.currentContainer.add_widget(self) def access(self): print("ATTACH") def _update(self, loadElements, container, parentName): for _index, item in enumerate(loadElements): localBox = BoxLayout(size_hint=(1, None), height=30) test = Button( markup=True, halign="left", valign="middle", padding_x= 10, font_size=15, text='[b]' + item['name'] + '[/b][u][i] Image[/i][/u]', color=self.engineRoot.engineConfig.getThemeTextColor(), background_normal= '', background_color=(self.engineRoot.engineConfig.getThemeBgSceneBtnColor()), on_press=partial(self.engineRoot.showCurrentAssetsEditor, item), size_hint=(1, None), height=30 ) localBox.add_widget(test) deleteAssetBtn = Button( markup=True, halign="left", valign="middle", padding_x= 10, font_size=15, text='[b]Delete[/b]', color=(self.engineRoot.engineConfig.getThemeCustomColor("alert")), background_normal= '', background_color=(self.engineRoot.engineConfig.getThemeCustomColor('background')), on_press=partial(self.engineRoot.showCurrentAssetsEditor, item), size_hint=(0.2, None), height=30 ) localBox.add_widget(deleteAssetBtn) container.add_widget(localBox) test.bind(size=test.setter('text_size')) if (_index==len(loadElements)-1): self.deepTest=0 def selfUpdate(self): self.clear_widgets() self.assetsStore = JsonStore(self.assetsPath) # call theme, improve aplha arg self.sceneScroller = GridLayout( orientation='lr-tb', size_hint=(1, None), height=400 ) self.sceneScroller.cols = 1 self.sceneScroller.size_hint_y= None self.sceneScroller.spacing = 1 self.sceneScroller.add_widget( Button( markup=True, text='[b]JSONN Explorer[/b]', color=self.engineRoot.engineConfig.getThemeTextColor(), size_hint=(1, None), background_normal= '', background_color=(self.engineRoot.engineConfig.getThemeBackgroundColor()), height=35 ) ) for _n_ in self.assetsStore.find(): print('nidza explore:', _n_) for _nsub_ in _n_: print('nidza sub explore:', _n_) self.add_widget(self.sceneScroller)