python类Environment()的实例源码

contracts.py 文件源码 项目:saffron 作者: Lamden 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __init__(self, name, sol_file_path):
        assert name != None, 'A name identifier must be provided to create a new contract instance.'
        _name, _address = database.contract_exists(name=name)
        assert _name is None and _address is None
        node_info = json.loads(open(os.environ['NODE_INFO_JSON']).read())
        self.web3 = Web3(Web3.HTTPProvider("http://127.0.0.1:{port}".format(port=node_info.get('rpcport'))))
        self.name = name
        self.is_deployed = None
        with open(sol_file_path) as f:
            self.sol = load_sol_file(f)
        self.template_json = Environment().from_string(database.input_json).render(name=self.name, sol=json.dumps(self.sol))
        self.output_json = compile_standard(json.loads(self.template_json))
        self.compiled_name = list(self.output_json['contracts'][self.name].keys())[0]
        self.contracts = self.output_json['contracts'][self.name][self.compiled_name]
        self.abi = self.contracts['abi']
        self.metadata = self.contracts['metadata']
        self.bytecode = self.contracts['evm']['deployedBytecode']['object']
        self.gas_estimates = self.contracts['evm']['gasEstimates']
        self.method_identifiers = self.contracts['evm']['methodIdentifiers']

        # set in deploy
        self.address = None
        self.instance = None
        self.defaulAccount = None
app.py 文件源码 项目:awesome-python3-webapp 作者: syusonn 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def init_jinja2(app,**kw):
    logging.info('init jinja2...')
    options = dict(
        autoescape = kw.get('autoescape',True),
        block_start_string = kw.get('block_start_string','{%'),
        block_end_string = kw.get('block_end_string','%}'),
        variable_start_string = kw.get('variable_start_string','{{'),
        variable_end_string = kw.get('variable_end_string','}}'),
        auto_reload = kw.get('auto_reload',True)
    )
    path = kw.get('path',None)
    if path is None:
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'templates')
    logging.info('set jinja2 template path:%s ' % path)
    env = Environment(loader=FileSystemLoader(path),**options)
    filters = kw.get('filters',None)
    if filters is not None:
        for name,f in filters.items():
            env.filters[name] = f
    app['__templating__'] = env     

# ??????
gen_template.py 文件源码 项目:powerdns-shell-wrapper 作者: opensource-expert 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def generate(self, zone, json_data=None):
        # compute local script location to find template_dir
        me = os.path.realpath(__file__)
        template_dir = os.path.dirname(me) + '/.'

        self.d['domain'] = zone

        # override with json
        if json_data:
            self.d.update(json.loads(json_data))

        env = Environment(loader=FileSystemLoader(template_dir))
        # add to_json filer in jinja2
        # so json can be dumped with in jinja2: {{ var | to_json }}
        env.filters['to_json'] = json.dumps

        template = env.get_template(self.zonetemplate)
        json_str = template.render(self.d)
        return json_str
tools.py 文件源码 项目:harrier 作者: samuelcolvin 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # TODO store the loader or env on the tool factory for faster partial builds
        # (this would need to cope with new files)
        self._loader = FrontMatterFileSystemLoader(self._config.jinja_directories)
        self._env = Environment(loader=self._loader)

        self._env.filters['S'] = self.static_file_filter

        self._file_ctxs = {}
        self._initialise_templates()

        self._ctx = self._config.context
        self._library = self._config.find_library()
        self._library_files = walk(self._library) if self._library else []
        self._extra_files = []
render.py 文件源码 项目:dockerfiles 作者: floydhub 项目源码 文件源码 阅读 59 收藏 0 点赞 0 评论 0
def render(search_root, project):
    template_paths = []
    matrix_dirs = []

    # traverse filesystem once and find out all matrix.yml and templates
    for cur_dir, dirs, files in os.walk(search_root):
        # TODO: hornor .gitignore
        for f in files:
            if f == 'matrix.yml':
                logger.info('Found matrix in %s', cur_dir)
                matrix_dirs.append(cur_dir)
            elif f.endswith('.jinja'):
                template_paths.append(os.path.join(cur_dir, f))

    # register templates with jinja environment
    jinja2_env = jinja2.Environment(loader=FilesLoader(template_paths))

    for maxtrix_dir in matrix_dirs:
        if project and os.path.basename(maxtrix_dir) != project:
            continue
        render_matrix(jinja2_env, maxtrix_dir)
templating.py 文件源码 项目:charm-nova-compute 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def render_and_write(template_dir, path, context):
    """Renders the specified template into the file.

    :param template_dir: the directory to load the template from
    :param path: the path to write the templated contents to
    :param context: the parameters to pass to the rendering engine
    """
    env = Environment(loader=FileSystemLoader(template_dir))
    template_file = os.path.basename(path)
    template = env.get_template(template_file)
    log('Rendering from template: %s' % template.name, level=DEBUG)
    rendered_content = template.render(context)
    if not rendered_content:
        log("Render returned None - skipping '%s'" % path,
            level=WARNING)
        return

    write(path, rendered_content.encode('utf-8').strip())
    log('Wrote template %s' % path, level=DEBUG)
templating.py 文件源码 项目:charm-nova-compute 作者: openstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, templates_dir, openstack_release):
        if not os.path.isdir(templates_dir):
            log('Could not locate templates dir %s' % templates_dir,
                level=ERROR)
            raise OSConfigException

        self.templates_dir = templates_dir
        self.openstack_release = openstack_release
        self.templates = {}
        self._tmpl_env = None

        if None in [Environment, ChoiceLoader, FileSystemLoader]:
            # if this code is running, the object is created pre-install hook.
            # jinja2 shouldn't get touched until the module is reloaded on next
            # hook execution, with proper jinja2 bits successfully imported.
            if six.PY2:
                apt_install('python-jinja2')
            else:
                apt_install('python3-jinja2')
app.py 文件源码 项目:python-awesome-web 作者: tianzhenyun 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def init_jinja2(app, **kwargs):
    logging.info('init jinja2...')
    options = dict(
        autoescape = kwargs.get('autoescape', True),
        block_start_string = kwargs.get('block_start_string', '{%'),
        block_end_string = kwargs.get('blcok_end_string', '%}'),
        variable_start_string = kwargs.get('variable_start_string', '{{'),
        variable_end_string = kwargs.get('variable_end_string', '}}'),
        auto_reload = kwargs.get('auto_reload', True)
    )
    path = kwargs.get('path', None)
    if path is None:
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
    logging.info('set jinja2 template path: {}'.format(path))
    env = Environment(loader = FileSystemLoader(path), **options)
    filters = kwargs.get('filters', None)
    if filters is not None:
        for name, f in filters.items():
            env.filters[name] = f
    app['__templating__'] = env
malboxes.py 文件源码 项目:malboxes 作者: GoSecure 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def prepare_packer_template(config, template_name):
    """
    Prepares a packer template JSON file according to configuration and writes
    it into a temporary location where packer later expects it.

    Uses jinja2 template syntax to generate the resulting JSON file.
    Templates are in templates/ and snippets in templates/snippets/.
    """
    try:
        template_fd = resource_stream(__name__,
                                     'templates/{}.json'.format(template_name))
    except FileNotFoundError:
        print("Template doesn't exist: {}".format(template_name))
        sys.exit(2)

    filepath = resource_filename(__name__, 'templates/')
    env = Environment(loader=FileSystemLoader(filepath), autoescape=False,
                      trim_blocks=True, lstrip_blocks=True)
    template = env.get_template("{}.json".format(template_name))

    # write to temporary file
    f = create_cachefd('{}.json'.format(template_name))
    f.write(template.render(config)) # pylint: disable=no-member
    f.close()
    return f.name
file_configuration.py 文件源码 项目:punch 作者: lgiordani 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, filepath, local_variables, global_variables=None):
        self.config = {}
        if global_variables:
            self.config.update(global_variables)

        new_local_variables = {}
        env = jinja2.Environment(undefined=jinja2.DebugUndefined)
        for key, value in local_variables.items():
            if six.PY2:
                value = value.decode('utf8')

            template = env.from_string(value)
            new_local_variables[key] = template.render(
                GLOBALS=global_variables)

        self.config.update(new_local_variables)
        self.path = filepath
modules.py 文件源码 项目:openshift-restclient-python 作者: openshift 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __jinja_render_to_file(cls, template_path, template_file, module_name,
                               temp_dir, module_path, **context):
        """
        Create the module from a jinja template.

        :param template_file: name of the template file
        :param module_name: the destination file name
        :param temp_dir: a temporary working dir for jinja
        :param context: dict of substitution variables
        :return: None
        """
        j2_tmpl_path = template_path
        j2_env = Environment(loader=FileSystemLoader(j2_tmpl_path), keep_trailing_newline=True)
        j2_tmpl = j2_env.get_template(template_file)
        rendered = j2_tmpl.render(dict(temp_dir=temp_dir, **context))
        with open(os.path.normpath(os.path.join(module_path, module_name)), 'wb') as f:
            f.write(rendered.encode('utf8'))
templating.py 文件源码 项目:charm-ceph-osd 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def render_and_write(template_dir, path, context):
    """Renders the specified template into the file.

    :param template_dir: the directory to load the template from
    :param path: the path to write the templated contents to
    :param context: the parameters to pass to the rendering engine
    """
    env = Environment(loader=FileSystemLoader(template_dir))
    template_file = os.path.basename(path)
    template = env.get_template(template_file)
    log('Rendering from template: %s' % template.name, level=DEBUG)
    rendered_content = template.render(context)
    if not rendered_content:
        log("Render returned None - skipping '%s'" % path,
            level=WARNING)
        return

    write(path, rendered_content.encode('utf-8').strip())
    log('Wrote template %s' % path, level=DEBUG)
__init__.py 文件源码 项目:zops 作者: bjinwright 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def create_initial_app(self):
        #Create app directory
        os.makedirs('app')
        template_path = Path(__file__).ancestor(1).child('templates')
        #Create Jinja2 Environment
        env = Environment(autoescape=False,
                          loader=FileSystemLoader(template_path))
        #Get flask and zappa_settings templates
        flask_app_template = env.get_template('flask.py.jinja2')
        zappa_settings_template = env.get_template(
            'zappa_settings.json.jinja2')
        #Create Flask app and zappa_settings.json files in the app directory
        with open('app/{app_name}.py'.format(app_name=self.app_name), 'w+') as f:
            f.write(flask_app_template.render(app_name=self.app_name, stage_name=self.stage_name))
        with open('app/zappa_settings.json'.format(app_name=self.app_name), 'w+') as f:
            f.write(zappa_settings_template.render(app_name=self.app_name,
                                                   stage_name=self.stage_name,
                                                   function_bucket=self.function_bucket,
                                                   aws_region_name=self.aws_region_name))
        #Copy the HTML template to the app/templates directory
        shutil.copytree(template_path.child('templates'), 'app/templates')
loader.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_caching(self):
        changed = False
        class TestLoader(loaders.BaseLoader):
            def get_source(self, environment, template):
                return u'foo', None, lambda: not changed
        env = Environment(loader=TestLoader(), cache_size=-1)
        tmpl = env.get_template('template')
        assert tmpl is env.get_template('template')
        changed = True
        assert tmpl is not env.get_template('template')
        changed = False

        env = Environment(loader=TestLoader(), cache_size=0)
        assert env.get_template('template') \
               is not env.get_template('template')

        env = Environment(loader=TestLoader(), cache_size=2)
        t1 = env.get_template('one')
        t2 = env.get_template('two')
        assert t2 is env.get_template('two')
        assert t1 is env.get_template('one')
        t3 = env.get_template('three')
        assert 'one' in env.cache
        assert 'two' not in env.cache
        assert 'three' in env.cache
ext.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_loop_controls(self):
        env = Environment(extensions=['jinja2.ext.loopcontrols'])

        tmpl = env.from_string('''
            {%- for item in [1, 2, 3, 4] %}
                {%- if item % 2 == 0 %}{% continue %}{% endif -%}
                {{ item }}
            {%- endfor %}''')
        assert tmpl.render() == '13'

        tmpl = env.from_string('''
            {%- for item in [1, 2, 3, 4] %}
                {%- if item > 2 %}{% break %}{% endif -%}
                {{ item }}
            {%- endfor %}''')
        assert tmpl.render() == '12'
utils.py 文件源码 项目:django-openapi-gen 作者: Ecognize 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self):
        self.loader = FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))
        self.env = Environment(loader = self.loader)
templating.py 文件源码 项目:charm-plumgrid-gateway 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _get_tmpl_env(self):
        if not self._tmpl_env:
            loader = get_loader(self.templates_dir, self.openstack_release)
            self._tmpl_env = Environment(loader=loader)
conftest.py 文件源码 项目:flash_services 作者: textbook 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def jinja():
    here = os.path.dirname(__file__)
    template_path = '{}/flash_services/templates'.format(here)
    return jinja2.Environment(loader=jinja2.FileSystemLoader(template_path))
s3_service.py 文件源码 项目:orca 作者: bdastur 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def generate_new_s3_lifecycle_policy_document(self,
                                                  policyobj):
        '''
        Generate a new S3 lifecycle policy document
        '''

        searchpath = get_absolute_path_for_file("./")
        templatefile = "./templates/s3_lifecycle_policy.j2"
        now = datetime.datetime.now()
        timestamp = "%s%s" % (str(now.microsecond), str(now.second))

        for rule in policyobj['rules']:
            if rule.get('id', None):
                rule['id'] = "rule-%s" % str(timestamp)

        print "policyobj: ", policyobj
        template_loader = jinja2.FileSystemLoader(searchpath=searchpath)
        env = jinja2.Environment(loader=template_loader,
                                 trim_blocks=False,
                                 lstrip_blocks=False)
        template = env.get_template(templatefile)
        data = template.render(policyobj)
        print "data: ", data

        jdata = json.loads(data)
        return jdata
gen_report.py 文件源码 项目:rca-evaluation 作者: sieve-microservices 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def write_template(template, path, **kwargs):
    template = Environment().from_string(template)
    content = template.render(**kwargs)
    print(path)
    with open(path, "w+") as f:
        f.write(content)


问题


面经


文章

微信
公众号

扫码关注公众号