def render_template(ctx, output: str, items, template, templates=None, **kwargs): if template is None: logger.debug("Loading default markdown") template = LazyFile(DEFAULT_MARKDOWN, 'r') elif isinstance(template, str): template = LazyFile(template, 'r') if templates is None: templates = dict() if template.name in templates: template_src = templates[template.name] else: env = Environment(loader=BaseLoader) env.filters['is_dict'] = is_dict template_src = env.from_string(template.read()) templates[template.name] = template_src if logger.isEnabledFor(DEBUG): logger.debug(f"Sending template items value of {items}") if output: logger.debug(f"Writing to {output.name}") render_args = dict(items=items, context=ctx.obj, **kwargs) result = template_src.render(render_args) if output: with open(output, 'w') as out: out.write(result) else: print(result)
def get_index_template(template_types): template = None template_types = list(template_types) if logger.isEnabledFor(DEBUG): logger.debug( f"Checking for template default for types: {template_types}") if len(template_types) == 1: if template_types[0] == 'git': logger.debug("Loading git template") template = LazyFile(DEFAULT_GIT) elif template_types[0] == 'github': logger.debug("Loading github template") template = LazyFile(DEFAULT_GITHUB_INDEX_VERSION) return template
def get_template(template, template_types, split_versions): if template is None: template_types = list(template_types) if logger.isEnabledFor(DEBUG): logger.debug( f"Checking for template default for types: {template_types}") if len(template_types) == 1: if template_types[0] == 'git': logger.debug("Loading git template") template = LazyFile(DEFAULT_GIT, 'r') elif template_types[0] == 'github': logger.debug("Loading github template") template = LazyFile( DEFAULT_GITHUB_VERSION if split_versions else DEFAULT_GITHUB, 'r') return template
def run(self, words_fn, guess_fn, exemplars=False): add_exemplars = self.returns_centers and exemplars with open(words_fn) as inf, LazyFile(guess_fn, "w") as outf: try: for line in inf: lemma_name, pos = line.strip().rsplit(",", 1) try: if add_exemplars: clus_obj, centers = self.clus_lemma( lemma_name, pos, True) else: clus_obj = self.clus_lemma(lemma_name, pos) centers = [] except NoSuchLemmaException: print(f"No such lemma: {lemma_name}", file=sys.stderr) else: for k, v in sorted(clus_obj.items()): num = k + 1 for ss in v: if add_exemplars: exemplar = "1" if ss in centers else "0" print( f"{lemma_name}.{num:02},{ss},{exemplar}", file=outf) else: print(f"{lemma_name}.{num:02},{ss}", file=outf) except Exception: # This is probably a partial guess: delete it to avoid getting # incorrect results outf.close() if exists(guess_fn): os.unlink(guess_fn) raise
def decrypt(input_container, output_medium): """Turn a container file back into its original media file.""" if not output_medium: if input_container.name.endswith(CONTAINER_SUFFIX): output_medium_name = input_container.name[:-len(CONTAINER_SUFFIX)] else: output_medium_name = input_container.name + MEDIUM_SUFFIX output_medium = LazyFile(output_medium_name, "wb") click.echo("In decrypt: %s" % str(locals())) container = load_from_json_bytes(input_container.read()) medium_content = _do_decrypt(container=container) with output_medium: output_medium.write(medium_content)
def write_events(location: str, files: Dict[str, List[str]]) -> None: makedirs(location) for fn, data in files.items(): with LazyFile(f'{location}/{fn}.csv', 'w', atomic=True) as temp: w = writer(temp, dialect=RdialDialect) w.writerow(FIELDS) for ev in data: w.writerow(ev)
def test_init(): # Test lazy loading (not pointing to a config file) config = Config() assert config.markup is json # Test loading with some defaults config = Config(defaults=dict(name='P.T. Anderson')) assert config['name'] == 'P.T. Anderson' # Test loading with an alternate markup engine config = Config(markup=toml) assert config.markup is toml # Test loading with a non-existent config file config = Config(LazyFile('tests/fixtures/nothing.json', 'w')) assert config == {} # Test loading with an existing config file config = Config(LazyFile('tests/fixtures/something.json', 'w')) assert config['title'] == 'Magnolia'
def encrypt(input_medium, output_container): """Turn a media file into a secure container.""" if not output_container: output_container = LazyFile(input_medium.name + CONTAINER_SUFFIX, "wb") click.echo("In encrypt: %s" % str(locals())) container_data = _do_encrypt(data=input_medium.read()) container_data_bytes = dump_to_json_bytes(container_data, indent=4) with output_container as f: f.write(container_data_bytes)