def dumps(obj): ''' Convenience function for running `dumps` using this encoder. Arguments --------- obj: :class:`LazySettings` Object to be converted to json friendly :class:`dict` ''' return json.dumps(obj, cls=TerraJSONEncoder)
def add_config_kvp(key, value): config_base_path, config_path = get_config_pathes() config_base = read_json_file(config_base_path) if not key in config_base.keys() and key != 'gitlab.token': print_red(f'Unknown config key \'{key}\'.') sys.exit(1) config = read_json_file(config_path) if os.path.exists(config_path) else {} config[key] = value config_json = jstyleson.dumps(config, indent=2) write_json_file(config_path, config_json)
def _do_song_guess(self, user, songs, participant): if len(songs) < 12: self.logger.info('song command incomplete') self.logger.debug(songs) return self.guesses['song'] = self._remove_stale_guesses( self.guesses['song'], user['username']) song_guess = OrderedDict() song_guess["Zelda's Lullaby"] = None song_guess["Epona's Song"] = None song_guess["Saria's Song"] = None song_guess["Sun's Song"] = None song_guess["Song of Time"] = None song_guess["Song of Storms"] = None song_guess["Minuet of Forest"] = None song_guess["Bolero of Fire"] = None song_guess["Serenade of Water"] = None song_guess["Requiem of Spirit"] = None song_guess["Nocturne of Shadow"] = None song_guess["Prelude of Light"] = None i = 0 for song in song_guess: guess = songs[i] songname = self._parse_songs(guess) if not songname: self.logger.info('Invalid song %s', guess) return song_guess[song] = songname i += 1 guess = SessionLogEntry(timestamp=datetime.now(), participant=participant.user_id, participant_name=participant.username, guess_type="Song", guess=jstyleson.dumps(song_guess).replace( ',', '\n'), session_points=participant.session_points, total_points=participant.total_points) self.database['current-session'].guesses.append(guess) song_guess['user-id'] = user['user-id'] song_guess['username'] = user['username'] song_guess['timestamp'] = datetime.now() self.guesses['song'].append(song_guess) self.logger.debug(song_guess)
def _do_medal_guess(self, user, medals, participant): if len(medals) < 5 or len(medals) < 6 and not self.state['freebie']: self.logger.info('Medal command incomplete') self.logger.debug(medals) return self.guesses['medal'] = self._remove_stale_guesses( self.guesses['medal'], user['username']) medal_guess = OrderedDict() medal_guess["forest"] = None medal_guess["fire"] = None medal_guess["water"] = None medal_guess["spirit"] = None medal_guess["shadow"] = None medal_guess["light"] = None i = 0 for medal in medal_guess: guess = medals[i] if guess not in self.guessables['dungeons'] and guess != 'free': self.logger.info('Invalid medal %s', guess) return if medal == self.state['freebie'] or guess == 'free': continue medal_guess[medal] = guess i += 1 guess = SessionLogEntry(timestamp=datetime.now(), participant=participant.user_id, participant_name=participant.username, guess_type="Medal", guess=jstyleson.dumps(medal_guess).replace( ',', '\n'), session_points=participant.session_points, total_points=participant.total_points) self.database['current-session'].guesses.append(guess) medal_guess['user-id'] = user['user-id'] medal_guess['username'] = user['username'] medal_guess['timestamp'] = datetime.now() self.guesses['medal'].append(medal_guess) self.logger.debug(medal_guess)
def __init__(self, config_location, is_dict_config=False, dict_config=None): """Read in configuration file and parse into specified values Args: config_location (str): valid filepath for file is_dict_config (bool): are we passing in a dictionary configuration directly dict_config (dict): dictionary object, if is_dict_config """ if is_dict_config: ext = None if dict_config is None: raise Exception("expected dict_config was None") if not isinstance(dict_config, dict): raise Exception("did not receive expected dict_config") dict_str = jstyleson.dumps(dict_config) config_str = Configuration.perform_any_config_fragment_substitution( dict_str) else: logging.info("Loading config file at {}".format(config_location)) self.config_location = config_location if os.path.exists(config_location): ext = os.path.splitext(config_location)[1].lower() if ext not in SUPPORTED_EXTS: raise ValueError( "config file at: {} has improper extension type - please use a .json or .yml file" .format(config_location)) with open(config_location, "r") as f: config_str = f.read() config_str = Configuration.perform_any_config_fragment_substitution( config_str) else: raise Exception( "config file at: {} not found".format(config_location)) if ext is None or ext == ".json": self.config = jstyleson.loads( config_str, object_pairs_hook=self.dict_raise_on_duplicates) elif ext in [".yaml", ".yml"]: self.config = yaml.load(config_str, Loader=yaml.FullLoader) assert isinstance(self.config, dict) # check top-level keys for k in self.config: if k not in ConfigurationSectionType.values(): msg = "Unsupported top-level key: %s. " % k msg += "Supported keys are %s" % str( ConfigurationSectionType.values()) raise ConfigurationError(msg) # metadata section can be optional self.config_metadata = None if ConfigurationSectionType.METADATA.value in self.config: self.config_metadata = self.config[ ConfigurationSectionType.METADATA.value] # implemetation_config section is required if not ConfigurationSectionType.IMPLEMENTATION_CONFIG.value in self.config: raise ConfigurationError( "Did not find required top-level key %s" % ConfigurationSectionType.IMPLEMENTATION_CONFIG.value) # keep a copy of the complete configuration self.complete_config = self.config.copy() # note: config is now just the implementation component of the dictionary self.config = self.config[ ConfigurationSectionType.IMPLEMENTATION_CONFIG.value] # store the dag object self.dag = ConfigurationDag(self.config) # populate configuration file string and hash self.config_string, self.config_hash = self._get_configuration_hash() # get the formatted time this file was instantiated self.config_time = datetime.datetime.now().strftime("%Y%m%d_%H%M") # parse the file into an internal config object self._parse_config() self.check_config()
def save(self): json_dict = {'recent_projects': self.recent_projects, 'open_notes': self.open_notes, 'accessed': self.recently_viewed} with open(self.file_name, mode='w', encoding='utf-8', errors='ignore') as f: f.write(json.dumps(json_dict))
print ("") print ("******************************************************************") print (" Input parameters ") print ("******************************************************************") print ("") # Parse JSON configuration file. # Raise exception if wrong number of inputs are provided to script. if len(sys.argv) != 2: raise Exception("Only provide a JSON config file as input!") json_input_file = open(sys.argv[1]) with open(sys.argv[1], 'r') as json_input_file: json_input_string = json_input_file.read() config = jstyleson.loads(json_input_string) jstyleson.dumps(config) pprint(config) print ("") print ("******************************************************************") print (" Operations ") print ("******************************************************************") print ("") print ("Fetching data from database ...") # Connect to SQLite database. try: database = sqlite3.connect(config['database']) except sqlite3.Error as error: