Ejemplo n.º 1
0
def load_jinja():
    #: prepare loaders
    #: loaders = ['_templates', theme]
    loaders = []
    root = os.path.abspath(os.path.dirname(__file__))
    tpl = os.path.join(root, '_templates')
    if os.path.exists(tpl):
        loaders.append(tpl)

    #: init jinja
    jinja = Environment(
        loader=FileSystemLoader(loaders),
        autoescape=False,  # blog don't need autoescape
    )
    #: initialize globals
    jinja.globals = {}

    #: default variables
    jinja.globals.update(
        {'system': {
            'name': 'Araledoc',
            'time': datetime.datetime.utcnow(),
        }})

    #: default filters
    jinja.filters.update({
        'xmldatetime':
        lambda o: o.strftime('%Y-%m-%dT%H:%M:%SZ'),
    })

    g.jinja = jinja
    return jinja
Ejemplo n.º 2
0
def render_file_name(file):
    DEBUG(1, "Processing FILENAME template " + file)
    try:
        fsload = FileSystemLoader(os.path.dirname(file))
        env = Environment(loader=fsload,
                          trim_blocks=1,
                          newline_sequence=j2_linesep)
        env.globals = globals()
        env.globals.update(locals())
        template = env.get_template(os.path.basename(file))
        result = template.render(env=os.environ)
    except TemplateNotFound:
        sys.stderr.write(
            "j2: Command line error TemplateNotFound: Can't open template " +
            file + '\n')
        exit(1)
    except TemplateSyntaxError as e:
        # Not sure which is the best here since this is an error in a file as opposed to cmdline error, for now, Ill do both
        sys.stderr.write("j2: Command line error TemplateSyntaxError: " +
                         e.filename + '(' + str(e.lineno) + ') ' + e.message +
                         '\n')
        sys.stderr.write(e.filename + '(' + str(e.lineno) +
                         '): j2 error TemplateSyntaxError:  ' + e.message +
                         '\n')
        exit(1)
    DEBUG(3, "Resulting FILENAME template " + file + " is " + result)
    return (result)
Ejemplo n.º 3
0
def environment_factory(template_dir=None, globals_=None):
    """Environment factory.

    Creates a Jinja2 Environment with the default templates and
    additional templates from `template_dir` loaded. If `globals` are
    provided, they are attached to the environment and thus available to
    all contexts.

    Parameters
    ----------
    template_dir : str
    globals_ : dict

    Returns
    -------
    jinja2.Environment

    """
    # first we try the custom templates, and fall back the ones provided
    # by blag
    loaders = []
    if template_dir:
        loaders.append(FileSystemLoader([template_dir]))
    loaders.append(PackageLoader('blag', 'templates'))
    env = Environment(loader=ChoiceLoader(loaders))
    if globals_:
        env.globals = globals_
    return env
Ejemplo n.º 4
0
def generate_html(config, output_dir):
    articles, categories, months, pages = index_blog_structure(config)

    file_loader = FileSystemLoader(
        os.path.join('themes', config['theme'], 'templates'))
    env = Environment(loader=file_loader)
    env.globals = get_globals(config, articles, categories, months, pages)

    clear_dir(output_dir)
    generate_home(config, output_dir, env)
    generate_archives_index(config, output_dir, env)

    for category in categories:
        generate_category_collection(config, output_dir, env, category)

    for month in months:
        generate_month_collection(config, output_dir, env, month)

    for article in articles:
        generate_article(config, output_dir, env, article)

    for page in pages:
        generate_page(config, output_dir, env, page)

    copy_assets(config, output_dir)
Ejemplo n.º 5
0
def render_file_template(file, output):
    DEBUG(1, "Processing FILE template " + file)
    templatepath = [os.path.dirname(file)] + args.TEMPLATEPATH
    j2['templatepath'] = os.pathsep.join(templatepath)
    j2['log'] = "J2: Template " + j2['templatepath']
    j2['logall'] = os.linesep.join(
        [j2['log'], j2['log1'], j2['log2'], j2['log3'], j2['log4']])
    try:
        fsload = FileSystemLoader(templatepath, encoding=j2_encoding)
        env = Environment(loader=fsload,
                          trim_blocks=(args.TRIM == 1),
                          newline_sequence=j2_linesep)
        env.globals = globals()
        env.globals.update(locals())
        template = env.get_template(os.path.basename(file))
        #output.write(codecs.encode(template.render(env=os.environ)+os.linesep, j2_encoding))
        output.write(template.render(env=os.environ) + os.linesep)
    except TemplateNotFound as e:
        sys.stderr.write(
            "j2: Command line error TemplateNotFound: Can't open template " +
            e.name + os.linesep)
        exit(1)
    except TemplateSyntaxError as e:
        # Not sure which is the best here since this is an error in a file as opposed to cmdline error, for now, Ill do both
        sys.stderr.write("j2: Command line error TemplateSyntaxError: " +
                         e.filename + '(' + str(e.lineno) + ') ' + e.message +
                         os.linesep)
        sys.stderr.write(e.filename + '(' + str(e.lineno) +
                         '): j2 error TemplateSyntaxError:  ' + e.message +
                         os.linesep)
        exit(1)
Ejemplo n.º 6
0
def test_athena__format_ctas_options_blank():
    env = Environment(loader=FileSystemLoader(path))
    env.globals = env.make_globals(d={'config': {}})
    module = env.get_template(fname).module
    expected = ''
    actual = module.athena__format_ctas_options()
    assert expected == actual
Ejemplo n.º 7
0
def load_jinja():
    #: prepare loaders
    #: loaders = ['_templates', theme]
    loaders = []
    root = os.path.abspath(os.path.dirname(__file__))
    tpl = os.path.join(root, '_templates')
    if os.path.exists(tpl):
        loaders.append(tpl)

    #: init jinja
    jinja = Environment(
        loader=FileSystemLoader(loaders),
        autoescape=False,  # blog don't need autoescape
    )
    #: initialize globals
    jinja.globals = {}

    #: default variables
    jinja.globals.update({
        'system': {
            'name': 'Araledoc',
            'time': datetime.datetime.utcnow(),
        }
    })

    #: default filters
    jinja.filters.update({
        'xmldatetime': lambda o: o.strftime('%Y-%m-%dT%H:%M:%SZ'),
    })

    g.jinja = jinja
    return jinja
 def runTests(self):
     """
     Run the tests prescribed in the configuration
     """
     sites = self.get_sites()
     templates_dir = os.path.join(sys.prefix, "etc/stashcache-tester/templates")
     
     # Parse the size of the test in bytes
     raw_testsize = humanfriendly.parse_size(get_option("testsize"))
     
     md5sum = self.createTestFile(raw_testsize, get_option("stashdir"))
     
     
     # Create the site specific tests
     env = Environment(loader=FileSystemLoader(templates_dir))
     
     
     
     env.globals = {
         "config_location": self.config_location,
         "stash_test_location": os.path.abspath(sys.argv[0]),
         "pythonpath": ":".join(sys.path),
         "testurl": get_option("testurl"),
         "localpath": get_option("stashdir"),
         "testsize": raw_testsize,
         "humantestsize": humanfriendly.format_size(raw_testsize)
     }
     
     test_dirs = []
     testingdir = get_option("testingdir")
     for site in sites:
         tmp_site = Site(site)
         test_dir = tmp_site.createTest(testingdir, env)
         test_dirs.append(test_dir)
     
     
     # Create the DAG from the template
     
     dag_template = env.get_template("dag.tmpl")
     test_dag = os.path.join(testingdir, "submit.dag")
     with open(test_dag, 'w') as f:
         f.write(dag_template.render(sites=sites, md5sum=md5sum))
         
     
     reduce_template = env.get_template("test_reduce.tmpl")
     reduce_submit = os.path.join(testingdir, "reduce.submit")
     with open(reduce_submit, 'w') as f:
         f.write(reduce_template.render())
         
     shutil.copyfile(os.path.join(templates_dir, "site_post.py"), os.path.join(get_option("testingdir"), "site_post.py"))
     os.chmod(os.path.join(get_option("testingdir"), "site_post.py"), 0755)
     
     # Start the DAG
     (stdout, stderr) = RunExternal("cd %s; condor_submit_dag submit.dag" % testingdir)
     logging.debug("output from condor_submit_dag: %s" % stdout)
     if stderr is not None or stderr is not "":
         logging.error("Error from condor_submit_dag: %s" % stderr)
Ejemplo n.º 9
0
def test_athena__format_ctas_options():

    env = Environment(loader=FileSystemLoader(path))
    env.globals = env.make_globals(d={'config': config_test_ctas_options})
    module = env.get_template(fname).module
    expected = ("WITH ( format='parquet', partitioned_by=ARRAY['col1', 'col2'], "
                "bucketed_by=ARRAY['col3'], external_location='s3://a/b/c/')")
    actual = module.athena__format_ctas_options()
    assert expected == actual
Ejemplo n.º 10
0
    def __str__(self):
        """
        """
        tmpl = Environment(loader=FileSystemLoader(
            searchpath=self.template_dir)).get_template(self.template_file)

        tmpl.globals = self.__dict__

        return tmpl.render()
Ejemplo n.º 11
0
 def fill_template(self, template, args):
     dirname, basename = os.path.split(self.options['template'])
     loader = ChoiceLoader([
         FileSystemLoader(dirname),
         PackageLoader('isotoma.recipe.ldap'),
         ])
     e = Environment(loader=loader)
     e.globals = dict(to_list=to_list)
     template = e.get_template(basename)
     return template.render(args)
Ejemplo n.º 12
0
def get_jinja_renderer(layout_dir, defaults, globals={}):
    jinja_loader = FileSystemLoader(layout_dir)
    jinja_env = Environment(loader=jinja_loader)
    jinja_env.filters['datetimeformat'] = lambda x, y: x.strftime(y)
    jinja_env.globals = globals

    def renderer(layout, context):
        t = jinja_env.get_template(layout)
        return t.render(context)

    return renderer
Ejemplo n.º 13
0
def environment(**options):
    loaders = []

    for app in getattr(settings, 'INSTALLED_APPS', []):
        loaders.append(ExtensionLoader(app, exclude=["html"]))

    env_kwargs = {
        'extensions': ['jinja2.ext.loopcontrols', 'jinja2.ext.with_', CompressorExtension],
        'line_comment_prefix': '# ',
        'loader': ChoiceLoader(loaders),
        'trim_blocks': True,
        'autoescape': True,
        'auto_reload': True,
        'cache_size': 1024
    }
    env_kwargs.update(getattr(settings, 'JINJA_ENVIRONMENT', {}))
    env = Environment(**env_kwargs)
    env.globals = {
        'url': url,
        'range': six.moves.range,
        'static': static,
        "_": _,
        "enumerate": enumerate,
        "utc_now": datetime.datetime.utcnow(),
        "timestamp": time.mktime(datetime.datetime.utcnow().timetuple())
    }

    env.globals.update(dict(
        all=all,
        unicode=str,
        isinstance=isinstance,
        format=format,
        sorted=sorted,
        min=min,
        max=max,
        zip=zip,
        pow=pow,
        divmod=divmod,
        map=map,
        str=str,
    ))

    env.globals.update(getattr(settings, 'JINJA_GLOBALS', {}))

    for f in ('capfirst', 'linebreaks', 'linebreaksbr', 'linenumbers',
              'pluralize', 'slugify', 'striptags',
              'timesince', 'timeuntil', 'title', 'truncatewords',
              'truncatewords_html', 'unordered_list', 'urlize',
              'urlizetrunc', 'yesno'):
        env.filters[f] = getattr(defaultfilters, f)
    env.filters['format_date'] = defaultfilters.date
    env.filters.update(getattr(settings, 'JINJA_FILTERS', {}))
    return env
Ejemplo n.º 14
0
def render_notebook(nb, context):
    env = Environment(extensions=['jinja2.ext.do'])
    env.filters['re_match'] = lambda target, expr: re.match(expr, str(target)
                                                            ).groups()
    env.globals = context

    nb.cells = [
        cell for cell in [render_cell(
            cell,
            env,
        ) for cell in nb.cells] if cell is not None
    ]
    return nb
Ejemplo n.º 15
0
 def DoTask(self):
     buildSetup = self.buildSetup
     menuTabs = (HomePage, DocsPage, WikiPage, ForumPage, DownloadPage)
     env = Environment(loader=FileSystemLoader(abspath(join(buildSetup.dataDir, "templates"))), trim_blocks=True)
     env.globals = {"files": GetSetupFiles(join(buildSetup.websiteDir, "downloads")), "MENU_TABS": menuTabs}
     env.filters = {"rst2html": rst2html}
     for page in menuTabs:
         path = os.path.abspath(join(buildSetup.websiteDir, page.outfile))
         try:
             os.makedirs(os.path.dirname(path))
         except os.error, exc:
             if exc.errno != errno.EEXIST:
                 raise
         env.get_template(page.template).stream(CURRENT=page).dump(path)
Ejemplo n.º 16
0
def get_template(template, args={}, output=None, render=True, stop=False):
    loader = False
    template_file = False

    if stop:
        import pdb; pdb.set_trace()

    if isinstance(template, tuple):
        loader = FileSystemLoader('%s/' % template[0])
        template_file = template[1]
    else:
        loader = FileSystemLoader('templates/')
        template_file = template

    env = Environment(loader=loader)
    env.filters['footnoter'] = footnoter
    env.filters['markdown'] = markdown
    env.filters['url'] = url
    env.filters['escaper'] = escaper
    env.filters['namespacer'] = namespacer
    env.filters['datetimeformat'] = datetimeformat
    env.filters['urlencode'] = urllib.quote

    settings = {}
    with open('settings.json', 'r') as f:
        settings = json.load(f)

    env.globals = {'base': settings['base'],
                   'year': 2011,
                   'article_url': get_list('magazine_src')[0]['filename']}

    template_object = env.get_template(template_file)

    if not render:
        return template_object

    rendered = template_object.render(args)

    if output:
        with open(output, 'w') as o:
           rendered = unicode(rendered)
           rendered = rendered.replace(u"\xe9", " ")
           rendered = rendered.replace(u"\u2019", " ")
           rendered = rendered.replace(u"\u00A0", " ")

           o.write(unicode(rendered))

    return rendered
Ejemplo n.º 17
0
def render_template(filename, dictionary={}):
    views_path = 'resources/views'
    environment = Environment(loader=PackageLoader('codemitts', views_path))

    authenticated = 'user' in cherrypy.session

    flash_messages = get_flash_messages()
    clear_flash_messages()

    environment.globals = {
        "session": cherrypy.session,
        "authenticated": authenticated,
        "flash_messages": flash_messages
    }
    template = environment.get_template(filename)
    return template.render(dictionary)
Ejemplo n.º 18
0
def generate():
    title_notes = store_get('title_notes', [])
    note_title_to_id, id_to_note_title = gn.get_note_maps(source_notes_dir)

    root_notes, note_links, note_backlinks = gn.get_note_graph(
        source_notes_dir, note_title_to_id, ["note", "summary"])

    orphan_notes = [n for n in root_notes if n not in title_notes]
    if len(orphan_notes) > 0:
        print("Orphan notes:")
        for orphan in orphan_notes:
            print(
                f"{path_cat(source_notes_dir, orphan)} - {id_to_note_title[orphan]}"
            )
        print()

    env = Environment(loader=FileSystemLoader(templates_dir),
                      autoescape=select_autoescape(['html']),
                      trim_blocks=True,
                      lstrip_blocks=True)
    env.globals = globals()

    for tname in env.list_templates():
        template = env.get_template(tname)

        out_path = path_cat(out_dir, tname)
        ensure_dir(path_dirname(out_path))
        template.stream(locals()).dump(out_path)

    gn.copy_changed(static_dir, out_dir)
    gn.copy_changed(source_files_dir, path_cat(out_dir, files_dir))

    success = True
    if c_needs_rebuild('weaver.c', './bin/weaver') or ex(
            f'./bin/weaver --has-js', echo=False) == 0:
        print('Building weaver...')
        if weaver_build(True) != 0:
            success = False
        else:
            print()

    # TODO: The HTML generator should only process source notes that changed.
    # Currently it generates all notes, all the time.
    if success:
        ex(f'./bin/weaver --generate-static --output-dir {path_cat(out_dir, notes_dir)}'
           )
Ejemplo n.º 19
0
 def render_html(self, template_name, **kwargs):
     current_user = self.get_current_user_info()
     kwargs.update({
         'settings': self.settings,
         'static_url':
         '/static',  #self.settings.get('static_path','/static'),
         'request': self.request,
         'current_user': current_user,
         'xsrf_token': self.xsrf_token,
         'xsrf_form_html': self.xsrf_form_html,
         'static_url_prefix': '/static'
     })
     template_dirs = [self.settings.get('template_path')]
     env = Environment(loader=FileSystemLoader(template_dirs))
     env.globals = ui_methods
     template = env.get_template(template_name)
     content = template.render(kwargs)
     self.write(content)
Ejemplo n.º 20
0
def build_index(notes, others, directory, template_path, depth):
    """Build HTML index of notes.

    Notes in year/[month/[day/]] folders are placed under appropriate headings.
    Other notes are organized in lexicographic order.
    """
    if os.path.exists(template_path):
        env = Environment(loader=FileSystemLoader(template_path))
    else:
        env = Environment(loader=PackageLoader("artnotizen"))
    libraries = download_libraries(_LIBRARY_URLS, directory)
    env.globals = {
        "notes": index_data(set(notes + others), directory, depth),
        "libraries": libraries,
    }
    template = env.get_template("index.html")
    with open(os.path.join(directory, "index.html"), "wb") as indexfile:
        print >> indexfile, template.render()
Ejemplo n.º 21
0
 def DoTask(self):
     buildSetup = self.buildSetup
     menuTabs = (HomePage, DocsPage, WikiPage, ForumPage, DownloadPage)
     env = Environment(loader=FileSystemLoader(
         abspath(join(buildSetup.dataDir, 'templates'))),
                       trim_blocks=True)
     env.globals = {
         "files": GetSetupFiles(join(buildSetup.websiteDir, "downloads")),
         "MENU_TABS": menuTabs,
     }
     env.filters = {'rst2html': rst2html}
     for page in menuTabs:
         path = os.path.abspath(join(buildSetup.websiteDir, page.outfile))
         try:
             os.makedirs(os.path.dirname(path))
         except os.error, exc:
             if exc.errno != errno.EEXIST:
                 raise
         env.get_template(page.template).stream(CURRENT=page).dump(path)
Ejemplo n.º 22
0
    def handle(self, *args, **options):
        # 遍历加载各app模块
        load_services('src', 'apps')

        # 从指定的路径获取模版
        temp_dir = options.get('template')
        if temp_dir:
            self._validate_template_dir(temp_dir)
            self.template_dir = temp_dir
        else:
            self.template_dir = abspath(join(
                dirname(dirname(__file__)), "templates", "proto_template"))

        env = Environment(
            loader=FileSystemLoader(self.template_dir),
            autoescape=False,
            trim_blocks=True,
            lstrip_blocks=True,
        )
        env.globals = env.make_globals({
            "isinstance": isinstance,
            "set": set,
            "list": list,
        })

        target_path = options.get('destination')
        if not os.path.exists(target_path):
            mkdir_if_not_exist(target_path)

        template = env.get_template("proto.tmpl")
        for app_name, meta in __proto_meta__.items():
            _modules = meta.modules
            _messages = self._process_messages(meta.messages, _modules, app_name)
            self._process_services(meta.services, _modules, _messages)
            _services = meta.services
            print(join(target_path, f"{app_name}.proto"))
            template.stream(
                package_name=app_name,
                modules=sorted(_modules),
                messages=_messages,
                services=_services,
            ).dump(join(target_path, f"{app_name}.proto"))
Ejemplo n.º 23
0
def build(source_dir, destination_dir):
    # TODO: blog post support
    try:
        with open(os.path.join(source_dir, '_config.yml')) as stream:
            config = yaml.safe_load(stream)
    except FileNotFoundError as ex:
        print(ex)
        print('No _config.yml found in source directory.')
        exit(1)
    except yaml.YAMLError:
        print('YAML syntax error in _config.yml.')
        exit(1)

    jinja_env = Environment(
        loader=FileSystemLoader(os.path.join(source_dir, '_templates')))
    jinja_env.globals = {'site': config, 'date': date}

    for filename, path_list in traverse_folder(source_dir):
        compile_file(jinja_env, filename, source_dir, destination_dir,
                     path_list)
Ejemplo n.º 24
0
def process_variables(config, manager):
    """Render all string elements of the config against defined variables."""
    env_params = {
        'block_start_string': '^^disabled^^',
        'block_end_string': '^^disabled^^',
        'variable_start_string': '{?',
        'variable_end_string': '?}'
    }
    if 'variables' not in config or config.get('variables') is False:
        return
    env = Environment(**env_params)
    if isinstance(config['variables'], bool):
        log.debug('trying to load variables from DB')
        variables = variables_from_db()
    else:
        log.debug('trying to load variables from file')
        variables = variables_from_file(manager.config_base, config['variables'])
        log.debug('updating DB with variable file contents')
        variables_to_db(variables)
    env.globals = variables
    _process(config, env)
    return config
Ejemplo n.º 25
0
def generate_page(page, lang, structure, out_dir, url=None):
    template_path = os.path.join(page.path, lang + '.html')
    page_path = page.url(lang) if url is None else url

    filename = out_dir + page_path

    print(f"generate_page {template_path} to {filename}")

    env = Environment(loader=FileSystemLoader(['templates']))
    loader = DirectLoader()

    env.globals = {
        "href": functools.partial(generate_link, lang=lang, page=page),
        "generate_image": functools.partial(generate_image, out_dir=out_dir),
        "check_exists": functools.partial(check_exists, out_dir=out_dir),
        "enumerate_folder": functools.partial(enumerate_folder,
                                              out_dir=out_dir),
        "language_code": lang,
    }
    template = loader.load(env, template_path, env.globals)

    dirname = os.path.dirname(filename)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    menu = io.StringIO()
    structure.printMenu(lang, menu, page)

    languages = io.StringIO()
    page.printLanguages(languages)

    args = {
        "title": page.title(lang),
        "menu": menu.getvalue(),
        "languages": languages.getvalue()
    }

    with open(filename, "w") as fh:
        fh.write(template.render(**args))
Ejemplo n.º 26
0
def process_variables(config, manager):
    """Render all string elements of the config against defined variables."""
    env_params = {
        'block_start_string': '^^disabled^^',
        'block_end_string': '^^disabled^^',
        'variable_start_string': '{?',
        'variable_end_string': '?}'
    }
    if 'variables' not in config or config.get('variables') is False:
        return
    env = Environment(**env_params)
    if isinstance(config['variables'], bool):
        log.debug('trying to load variables from DB')
        variables = variables_from_db()
    else:
        log.debug('trying to load variables from file')
        variables = variables_from_file(manager.config_base,
                                        config['variables'])
        log.debug('updating DB with variable file contents')
        variables_to_db(variables)
    env.globals = variables
    _process(config, env)
    return config
Ejemplo n.º 27
0
def setup_jinja_environment(alerts):
    jinja_loader = ChoiceLoader([
        FileSystemLoader(str(TEMPLATES)),
        FileSystemLoader(str(VIEWS)),
        PrefixLoader(
            {'govuk_frontend_jinja': PackageLoader('govuk_frontend_jinja')})
    ])

    env = Environment(loader=jinja_loader, autoescape=True)
    env.filters['file_fingerprint'] = file_fingerprint
    env.filters['formatted_list'] = formatted_list
    env.filters['paragraphize'] = paragraphize
    env.filters['get_url_for_alert'] = jinja_filter_get_url_for_alert
    env.globals = {
        'font_paths': [
            item.relative_to(DIST)
            for item in DIST.glob('alerts/assets/fonts/*.woff2')
        ],
        'alerts':
        alerts,
    }

    return env
Ejemplo n.º 28
0
def parse_markdown_with_template(filepath: Path, ctx: dict, template_dir: str):
    metadata, content = parse_markdown_file_with_fm(filepath)
    env = Environment(
        loader=FileSystemLoader(template_dir), trim_blocks=True, lstrip_blocks=True
    )
    env.globals = ctx.get("__globals", {})
    try:
        template_name = metadata.pop("__template")
    except KeyError as e:
        logging.error(f"File {filepath} does not specify a template.")
        raise e
    ctx["template"] = template_name
    try:
        template = env.get_template(template_name)
    except TemplateNotFound as e:
        logging.error(f"Could not locate template {template_name}.")
        raise e
    special_keys = [k[2:] for k in metadata.keys() if k[0:2] == "__"]
    for key in special_keys:
        ctx[key] = metadata.pop(key)
    output = template.render({**metadata, "content": content})
    filepath = filepath.with_suffix(".html")
    ctx.update({"output": output})
    return ctx
Ejemplo n.º 29
0
	def setUp(self):
		self.patchers = {p: patch(p) for p in {
				'os.path.isfile'}}
		self.addCleanup(lambda: [p.stop() for p in self.patchers.values()])
		for p in self.patchers.values():
			p.start()
		os.path.isfile.side_effect = lambda t: os.path.basename(t) in TEMPLATES

		self.module = Flow('mymodule', {
			'to': 'outdir',
			'extension': '.html',
			'context': {'modulevar': 'modulevar'},
		})
		testfile = 'test.markdown'
		self.init = Initializing(
				builddir='.build/',
				sourceroot=self.module.name,
				sourcepath=os.path.join(self.module.name, testfile),
				destroot=self.module.destroot,
				extension=self.module.extension)
		env = Environment(loader=DictLoader(TEMPLATES))
		env.filters = FILTERS
		env.globals = GLOBALS
		self.view = Compiling(
				env=env,
				modules=MODULES,
				templatedir='templates',
				builddir='.build/',
				sourceroot=self.module.name,
				sourcepath=os.path.join(self.module.name, testfile),
				destroot=self.module.destroot,
				extension=self.module.extension,
				processes=MagicMock(),
				dependencies=MagicMock(autospec=Graph),
				refresher=MagicMock(autospec=Refresher))
		self.module.render = MagicMock(side_effect=self.module.render)
Ejemplo n.º 30
0
from datetime import datetime

from jinja2 import Environment, FileSystemLoader
from twisted.web.http import RESPONSES

from helper.database import DatabaseHelper
from helper.permission import is_anybody
from localization import SITE_NAME
from model.board import Board


jinja2_env = Environment(loader=FileSystemLoader("template", encoding="utf-8"),
                         extensions=['jinja2.ext.with_'])
jinja2_env.globals = {
    "site_name": SITE_NAME,
    "datetime": datetime,
    "getattr": getattr,
}


def get_template(name, parent=None, glob=None):
    return jinja2_env.get_template(name, parent, glob)


def render_template(name, request, context=None):
    if context == None:
        context = dict()
    board_query = request.dbsession.query(Board).filter(Board.enabled).order_by(Board.repr_order.asc())
    board_meta = {
        "somoim": [(board.name, board.repr) for board in board_query.filter(Board.classification == "somoim")],
        "normal": [(board.name, board.repr) for board in board_query.filter(Board.classification == "normal")],
Ejemplo n.º 31
0
# -*- coding: utf-8 -*-

import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header

from flask import g, url_for
from jinja2 import Environment, FileSystemLoader

from dnsforever.models import EmailValidation, FindPasswd
from dnsforever.config import smtp_ssl, smtp_host, smtp_port, smtp_account

email_env = Environment(
    loader=FileSystemLoader(os.path.dirname(__file__) + '/templates'))
email_env.globals = {'g': g, 'url_for': url_for}

__all__ = ['email_validation']


def send_text_email(to, subject, body):
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = '*****@*****.**'
    msg['To'] = to

    if not smtp_ssl:
        s = smtplib.SMTP(smtp_host, smtp_port)
    else:
        s = smtplib.SMTP_SSL(smtp_host, smtp_port)
Ejemplo n.º 32
0
def load_jinja():
    #: prepare loaders
    #: loaders = ['_templates', theme]
    loaders = []
    tpl = os.path.abspath('_templates')
    if os.path.exists(tpl):
        loaders.append(tpl)

    theme = os.path.join(os.path.abspath('_themes'), settings.theme)
    if not os.path.exists(theme):
        theme = os.path.join(g.liquid_directory, '_themes', settings.theme)

    #: global variable
    g.theme_directory = theme

    theme_template = os.path.join(theme, 'templates')
    if os.path.exists(theme_template):
        loaders.append(theme_template)

    #: load default theme template always
    default_template = os.path.join(
        g.liquid_directory, '_themes/default/templates'
    )
    if default_template != theme_template:
        loaders.append(default_template)

    #: init jinja
    jinja = Environment(
        loader=FileSystemLoader(loaders),
        autoescape=False,  # blog don't need autoescape
        extensions=settings.template_extensions or [],
    )
    #: initialize globals
    jinja.globals = {}

    #: load template variables
    jinja.globals.update({
        'site': settings.site,
        'template': settings.template_variables,
    })

    #: load theme variables
    config = {}
    theme_config = os.path.join(theme, 'settings.py')
    if os.path.exists(theme_config):
        execfile(theme_config, {}, config)

    #: user can reset theme variables
    config.update(settings.theme_variables)
    jinja.globals.update({'theme': config})

    #: default variables
    jinja.globals.update({
        'system': {
            'name': 'Felix Felicis',
            'version': liquidluck.__version__,
            'homepage': liquidluck.__homepage__,
            'time': datetime.datetime.utcnow(),
        }
    })

    #: function helpers
    jinja.globals.update({
        'content_url': content_url,
        'static_url': static_url(os.path.join(theme, 'static')),
    })

    #: load theme filters
    config = {}
    theme_config = os.path.join(theme, 'filters.py')
    if os.path.exists(theme_config):
        execfile(theme_config, {}, config)

    jinja.filters.update(config)

    #: load filters from settings
    filters = settings.template_filters or {}
    for k, v in filters.items():
        jinja.filters.update({k: import_object(v)})

    #: default filters
    jinja.filters.update({
        'xmldatetime': lambda o: o.strftime('%Y-%m-%dT%H:%M:%SZ'),
        'permalink': permalink,
    })

    #: load resource
    g.resource['posts'] = g.public_posts
    g.resource['pages'] = g.pure_pages
    jinja.globals.update({
        'resource': g.resource,
    })

    g.jinja = jinja
    return jinja
Ejemplo n.º 33
0
        read_recipe_file(recipe_file) for recipe_file in recipe_files
    ]

    # Parse
    recipes = [
        parse_to_recipe(recipe_content) for recipe_content in recipe_contents
    ]

    # Render
    env = Environment(
        loader=PackageLoader("recipe_compiler", "templates"),
        autoescape=select_autoescape(["html"]),
    )

    # Handles the path setting for production versus local
    # (Production has /DevCookbook/ prepended to the path)
    env.globals = {"path_base": "/DevCookbook/" if target == "prod" else "/"}

    home_page = render_home_page(recipes, env)
    contribute_page = render_contribute_page(env)
    recipe_pages = zip(
        [recipe.slug for recipe in recipes],
        [render_recipe_page(recipe, env) for recipe in recipes],
    )

    # Write
    write_home_page(home_page)
    write_page("contribute", contribute_page)
    for recipe_slug, recipe_page in recipe_pages:
        write_page(recipe_slug, recipe_page)
Ejemplo n.º 34
0
We love free & open-source software. Sound like you? Get involved!
https://ocf.io/staff

OCF volunteers hold weekly staff hours to provide support:
    https://ocf.io/staff-hours

    Need help connecting to the OCF?
    https://ocf.io/ssh

    Need to reset your account password?
    https://ocf.io/password"""

jinja_mail_env = Environment(loader=PackageLoader('ocflib', ''))
jinja_mail_env.globals = {
    'mail_signature': MAIL_SIGNATURE,
}


def email_for_user(username, check_exists=True):
    """Return email for a user.

    Currently, just appends @ocf.berkeley.edu, but could eventually do
    something more complicated.
    """
    if check_exists:
        from ocflib.account.search import user_exists
        if not user_exists(username):
            raise ValueError('Account "{}" does not exist.'.format(username))

    return '{}@ocf.berkeley.edu'.format(username)
Ejemplo n.º 35
0
# -*- coding: utf-8 -*-

import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header

from flask import g, url_for
from jinja2 import Environment, FileSystemLoader

from dnsforever.models import EmailValidation, FindPasswd
from dnsforever.config import smtp_ssl, smtp_host, smtp_port, smtp_account

email_env = Environment(loader=FileSystemLoader(os.path.dirname(__file__) +
                                                '/templates'))
email_env.globals = {'g': g, 'url_for': url_for}

__all__ = ['email_validation']


def send_text_email(to, subject, body):
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = '*****@*****.**'
    msg['To'] = to

    if not smtp_ssl:
        s = smtplib.SMTP(smtp_host, smtp_port)
    else:
        s = smtplib.SMTP_SSL(smtp_host, smtp_port)
Ejemplo n.º 36
0
from .app import app
from .helpers import humanize_date, humanize_money

# Global variables in the Jinga templates.
globals = {
    'business': app.config['email']['business'],
    'humanize_date': humanize_date,
    'humanize_money': humanize_money
}

path = app.config['email']['templates_path']
notify_templates = Environment(loader=FileSystemLoader(path +
                                                       '/notifications'),
                               undefined=StrictUndefined)
notify_templates.globals = globals
receipt_templates = Environment(loader=FileSystemLoader(path + '/receipts'),
                                undefined=StrictUndefined)
receipt_templates.globals = globals


def send_email(from_address, subject, txt_rendered, recipient, html):
    msg_root = MIMEMultipart('related')
    msg_root['Subject'] = subject
    msg_root['From'] = from_address
    msg_root['To'] = recipient

    msg_alternative = MIMEMultipart('alternative')
    msg_root.attach(msg_alternative)

    msg_alternative.attach(MIMEText(txt_rendered, 'plain'))
Ejemplo n.º 37
0
import boto
import time
import datetime
from jinja2 import Environment, FileSystemLoader, StrictUndefined
from shared.helpers import humanize_date, humanize_money

from .app import app

# Global variables in the Jinga templates.
globals = {'business': app.config['email'][
    'business'], 'humanize_date': humanize_date, 'humanize_money': humanize_money}

notify_templates = Environment(
    loader=FileSystemLoader('stripe-hooks-emails/notifications'), undefined=StrictUndefined)
notify_templates.globals = globals

receipt_templates = Environment(
    loader=FileSystemLoader('stripe-hooks-emails/receipts'), undefined=StrictUndefined)
receipt_templates.globals = globals


def ses_connection():
    return boto.connect_ses(
        aws_access_key_id=app.config['AWS_ACCESS_KEY'],
        aws_secret_access_key=app.config['AWS_SECRET_KEY'])


def send_receipt(key, recipient, data=None):
    "Sends a receipt type of notification to a user"
    # If we don't have an ID, which we shouldn't, default it.
    if data is None:
Ejemplo n.º 38
0
from jinja2 import Environment, PackageLoader
from presence_analyzer.main import app
from presence_analyzer.utils import (
    jsonify,
    get_data,
    mean, group_by_weekday,
    seconds_since_midnight,
    group_start_end_by_weekday
)


import logging
log = logging.getLogger(__name__)  # pylint: disable-msg=C0103
env = Environment(loader=PackageLoader('presence_analyzer', 'templates'))
env.globals = {'url_for': url_for}


@app.route('/')
def mainpage():
    """
    Redirects to front page.
    """
    return redirect('/templates/presence_weekday')


@app.route('/templates/presence_start_end')
def presence_start_end_template():
    """
    Generates template for presence_start_end view
    """
Ejemplo n.º 39
0
    ]

    # Parse
    recipes = [
        parse_to_recipe(recipe_content) for recipe_content in recipe_contents
    ]

    # Render
    env = Environment(
        loader=PackageLoader("recipe_compiler", "templates"),
        autoescape=select_autoescape(["html"]),
    )

    # Handles the path setting for production versus local
    # (Production has /cookbook/ prepended to the path)
    env.globals = {"path_base": "/"}

    home_page = render_home_page(recipes, env)
    # contribute_page = render_contribute_page(env)
    recipe_pages = zip(
        [recipe.slug for recipe in recipes],
        [render_recipe_page(recipe, env) for recipe in recipes],
    )

    # Minify html
    if target == 'prod':
        home_page = htmlmin.minify(home_page, remove_empty_space=True)
        recipe_pages = map(
            lambda page:
            [page[0],
             htmlmin.minify(page[1], remove_empty_space=True)], recipe_pages)
Ejemplo n.º 40
0
# -*- coding: utf-8 -*-
from datetime import datetime

from jinja2 import Environment, FileSystemLoader
from twisted.web.http import RESPONSES

from helper.database import DatabaseHelper
from helper.permission import is_anybody
from localization import SITE_NAME
from model.board import Board

jinja2_env = Environment(loader=FileSystemLoader("template", encoding="utf-8"),
                         extensions=['jinja2.ext.with_'])
jinja2_env.globals = {
    "site_name": SITE_NAME,
    "datetime": datetime,
    "getattr": getattr,
}


def get_template(name, parent=None, glob=None):
    return jinja2_env.get_template(name, parent, glob)


def render_template(name, request, context=None):
    if context == None:
        context = dict()
    board_query = request.dbsession.query(Board).filter(
        Board.enabled).order_by(Board.repr_order.asc())
    board_meta = {
        "somoim":
Ejemplo n.º 41
0
from datatypes import Calendar, SEMESTERS, MONTHS, WEEKDAYS
from jinja2 import Environment, FileSystemLoader
from os import path
from webapp2 import uri_for

JINJA_ENVIRONMENT = Environment(loader=FileSystemLoader(
    path.join(path.dirname(__file__), '_templates')),
                                extensions=['jinja2.ext.autoescape'],
                                autoescape=True)
JINJA_ENVIRONMENT.globals = {
    'uri_for': uri_for,
    'range': range,
    'current_sem': Calendar.current_sem,
    'current_year': Calendar.current_year,
    'semesters': SEMESTERS,
    'months': MONTHS,
    'weekdays': WEEKDAYS,
}
JINJA_ENVIRONMENT.trim_blocks = True
JINJA_ENVIRONMENT.lstrip_blocks = True


def get_template(name, parent=None, globals=None):
    return JINJA_ENVIRONMENT.get_template(name + '.html', parent, globals)
Ejemplo n.º 42
0
		layout = TextAndCodeLayout(s, basePath, env, index)
	elif layoutType == 'VideoAndCode':
		layout = VideoAndCodeLayout(s, basePath, env, index)
	f = open(outDir + '/step' + str(index) + '.html', 'w')
	f.write(layout.generate())
	f.close()
	
env = Environment(loader=PackageLoader('imcodes', 'templates'));
env.globals = {
	"SCRIPTS": 
		["http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js",
		 "http://cdnjs.cloudflare.com/ajax/libs/codemirror/4.6.0/codemirror.js",
		 "http://cdnjs.cloudflare.com/ajax/libs/codemirror/4.6.0/mode/javascript/javascript.min.js",
		 "http://cdnjs.cloudflare.com/ajax/libs/codemirror/4.6.0/mode/python/python.min.js",
		 "http://cdn.popcornjs.org/code/dist/popcorn-complete.min.js",
	   "skulpt/skulpt.js",
		 "skulpt/skulpt-stdlib.js"],
	"STYLES":
		["http://yui.yahooapis.com/pure/0.5.0/pure-min.css",
		 "http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css",
	   "http://cdnjs.cloudflare.com/ajax/libs/codemirror/4.6.0/codemirror.min.css",
		 "common.css"]
};

def generate(yamlFile, inDir, outDir):
	# Load the YAML info
	f = open(inDir + '/' + yamlFile, 'r')
	moduleYaml = yaml.load(f.read())
	f.close()	
	env.globals["numSteps"] = len(moduleYaml['Steps']);
	env.globals["range"] = range
Ejemplo n.º 43
0
import inspect
import socket
import subprocess
from email.utils import parseaddr

from jinja2 import Environment
from jinja2 import PackageLoader

import ocflib.account.validators
import ocflib.constants as constants
import ocflib.misc.validators as validators


jinja_mail_env = Environment(loader=PackageLoader('ocflib', ''))
jinja_mail_env.globals = {
    'mail_signature': constants.MAIL_SIGNATURE,
}


def email_for_user(username):
    """Return email for a user.

    Currently, just appends @ocf.berkeley.edu, but could eventually do
    something more complicated."""

    ocflib.account.validators.validate_username(username, check_exists=True)
    return '{}@ocf.berkeley.edu'.format(username)


def send_mail_user(user, subject, body, sender=constants.MAIL_FROM):
    """Send a plan-text mail message to a user."""
Ejemplo n.º 44
0
# coding: utf-8

from jinja2 import Environment, PackageLoader
from application.common import common_globals

environment = Environment(loader=PackageLoader(__name__, '.'))
environment.globals = common_globals
Ejemplo n.º 45
0
 def create_jinja_env(self):
     env = Environment(
         loader=FileSystemLoader(str(self.ctx["blueprint_folder"])))
     env.globals = self.ctx
     return env
Ejemplo n.º 46
0
    def make_stats(self,
                   access_token,
                   user_id,
                   stat_libs,
                   result_folder='result',
                   post_message_func=None,
                   post_progress_func=None,
                   callback=None):

        self.cleanup()

        if post_message_func:
            self._post_message = post_message_func
        if post_progress_func:
            self._post_progress = post_progress_func

        self._setup(access_token, user_id)

        try:
            requests.get(
                "http://138.68.106.140:1337/send_usage?u1={}&u2={}".format(
                    self.user1_id, self.user2_id),
                timeout=0.5)
        except Exception:
            pass

        start_time = time.clock()
        self._prepare_data()

        _msg("Generating main statistics: ")
        main_stat = self.main_stat()
        _done()

        for lib in stat_libs:
            import_module(lib)

        os.makedirs(os.path.join(result_folder, 'stat'), exist_ok=True)
        page_list = []

        for stat in self._stat_list:
            _msg('Running "{}" stat module: '.format(stat['name']))
            res = ''
            if stat['name'] == "График времени сообщений":
                pass
            res = stat['func']()
            if res:
                filename = stat['filename']
                n = os.path.join(result_folder, 'stat', filename)
                page_list.append({
                    'name': stat['name'],
                    'link': os.path.join('stat', filename)
                })
                open(n, "w", encoding='utf-8').write(res)
            _done()

        env = Environment(loader=FileSystemLoader(
            os.path.join(self.base_dir, 'vk_basic_stats')))
        env.globals = self.template_globals

        res = env.get_template('main_template.html').render({
            'stat_pages':
            page_list,
            'main_stat_list':
            main_stat['list'],
            'vars':
            main_stat
        })

        open(os.path.join(result_folder, 'result.html'), "w",
             encoding='utf-8').write(res)

        _msg("Statistics is done in {}s.\n".format(
            round(time.clock() - start_time, 3)))

        if callback:
            callback()
Ejemplo n.º 47
0
def load_jinja():
    #: prepare loaders
    #: loaders = ['_templates', theme]
    loaders = []
    tpl = os.path.abspath('_templates')
    if os.path.exists(tpl):
        loaders.append(tpl)

    theme = find_theme()

    #: global variable
    g.theme_directory = theme

    theme_template = os.path.join(theme, 'templates')
    if os.path.exists(theme_template):
        loaders.append(theme_template)

    #: load default theme template always
    default_template = os.path.join(
        g.liquid_directory, '_themes/default/templates'
    )
    if default_template != theme_template:
        loaders.append(default_template)

    #: init jinja
    jinja = Environment(
        loader=FileSystemLoader(loaders),
        autoescape=False,  # blog don't need autoescape
        extensions=settings.writer.get('extensions') or [],
    )
    #: initialize globals
    jinja.globals = {}

    #: load template variables
    jinja.globals.update({
        'site': settings.site,
        'template': settings.template.get("vars") or {},
    })

    #: load theme variables
    config = {}
    theme_config = os.path.join(theme, 'settings.py')
    if os.path.exists(theme_config):
        logging.warn('settings.py in theme is deprecated since 3.4')
        logging.warn('the name should be changed to theme.py')
        execfile(theme_config, {}, config)
    theme_config = os.path.join(theme, 'theme.py')
    if os.path.exists(theme_config):
        execfile(theme_config, {}, config)

    #: user can reset theme variables
    config.update(settings.theme.get('vars') or {})
    #: keep namespace to the latest variables
    settings.theme['vars'] = config
    jinja.globals.update({'theme': config})

    #: default variables
    now = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
    jinja.globals.update({
        'system': {
            'name': 'Felix Felicis',
            'version': liquidluck.__version__,
            'homepage': liquidluck.__homepage__,
            'time': now,
        }
    })

    #: function helpers
    jinja.globals.update({
        'content_url': content_url,
        'static_url': static_url(os.path.join(theme, 'static')),
    })

    #: load theme filters
    config = {}
    theme_config = os.path.join(theme, 'filters.py')
    if os.path.exists(theme_config):
        execfile(theme_config, {}, config)

    jinja.filters.update(config)

    #: load filters from settings
    filters = settings.template.get("filters") or {}
    for k, v in filters.items():
        jinja.filters.update({k: import_object(v)})

    #: default filters
    jinja.filters.update({
        'xmldatetime': xmldatetime,
        'feed_updated': feed_updated,
        'permalink': permalink,
        'tag_url': tag_url,
        'year_url': year_url,
        'wiki_link': wiki_link,
    })

    #: load resource
    g.resource['posts'] = g.public_posts
    g.resource['pages'] = g.pure_pages
    jinja.globals.update({
        'resource': g.resource,
    })

    g.jinja = jinja
    return jinja
Ejemplo n.º 48
0
import os, importlib, markdown, pprint, data
from jinja2 import Environment, FileSystemLoader

# Initialize components for manipulating content before it is written out.
md = markdown.Markdown(
    extensions = ['extra', 'codehilite', 'meta', 'wikilinks'],
    output_format = 'html5'
)
jn = Environment(loader = FileSystemLoader(['.', 'templates']))
jn.globals = dict(jn.globals, **data.data)


def render(template, data):
    template = jn.get_template(template)
    return template.render(**data)


def tyrant(folder):
    """Convert tyrant folders into a static website."""
    tyrant_file = importlib.import_module('content.' + folder)
    target_dir = "/".join(tyrant_file.__path__) + '/data/'

    # Convert Data.
    pages = []
    for page in os.listdir(target_dir):
        if page.endswith('markdown') and os.path.isfile(target_dir + page):
            with open(target_dir + page) as pagedata:
                pages.append({
                    'data': md.convert(pagedata.read()),
                    'meta': md.Meta,
                    'name': page.rsplit('.', 1)[0]
Ejemplo n.º 49
0
        formatter = HtmlFormatter()
        return highlight(text, lexer, formatter)

def xmldatetime(value):
    date = datetime.datetime.fromtimestamp(value)  
    return date.strftime('%Y-%m-%d %H:%M')

def lastupdatetime(nodes):
    try:
        ret = xmldatetime(nodes[0].timestamp)
    except IndexError:
        ret = xmldatetime(0)
    return ret

def markdown(data):
    renderer = BleepRenderer()
    md = m.Markdown(renderer,
         extensions=m.EXT_FENCED_CODE | m.EXT_NO_INTRA_EMPHASIS)
    return md.render(data) 

def length(data):
    return len(data)

configs = getconfig()
app = configs.get('app')
theme = configs.get('theme')
env = Environment(loader=FileSystemLoader(os.path.join(app,'themes',theme,'templates')))
dfilter = {'xmldatetime':xmldatetime,'markdown':markdown,'length':length,'lastupdatetime':lastupdatetime}
env.filters = dfilter
env.globals = configs