Пример #1
0
    def interpolate(self_, string, stacklevel=1, name=None, self=None):
        """
        Interpolate a string.

        You can provide temporary ``self`` object with that keyword
        argument.

        This handles exceptions internally.

        The variable ``name`` is used to name the string.  Alternately
        it can look up ``stacklevel`` frames to find the location
        where the literal ``string`` is given (for error reports).
        """
        ## FIXME: maybe I should actually use "self" somewhere?
        if name is None:
            name = self_.name
            if stacklevel:
                try:
                    caller = sys._getframe(stacklevel)
                except ValueError:
                    pass
                else:
                    name = caller.f_globals.get('__name__') or name
        tmpl = Template(string, name=name)
        try:
            old_self = None
            if self is not None:
                old_self = self_.dict.get('self')
                self_.dict['self'] = self
            return tmpl.substitute(self_.dict)
        finally:
            if old_self is not None:
                self_.dict['self'] = old_self
            elif 'self' in self_.dict:
                del self_.dict['self']
 def generate(self, src, dst, **kwargs):
     namespace = self.get_namespace()
     namespace.update(kwargs)
     # pylint: disable-msg=C0321
     with open(src, 'rb') as src_stream, open(dst, 'wb') as dst_stream:
         template = Template(src_stream.read())
         dst_stream.write(template.substitute(**namespace))
Пример #3
0
    def interpolate(self_, string, stacklevel=1, name=None, self=None):
        """
        Interpolate a string.

        You can provide temporary ``self`` object with that keyword
        argument.

        This handles exceptions internally.

        The variable ``name`` is used to name the string.  Alternately
        it can look up ``stacklevel`` frames to find the location
        where the literal ``string`` is given (for error reports).
        """
        ## FIXME: maybe I should actually use "self" somewhere?
        if name is None:
            name = self_.name
            if stacklevel:
                try:
                    caller = sys._getframe(stacklevel)
                except ValueError:
                    pass
                else:
                    name = caller.f_globals.get('__name__') or name
        tmpl = Template(string, name=name)
        try:
            old_self = None
            if self is not None:
                old_self = self_.dict.get('self')
                self_.dict['self'] = self
            return tmpl.substitute(self_.dict)
        finally:
            if old_self is not None:
                self_.dict['self'] = old_self
            elif 'self' in self_.dict:
                del self_.dict['self']
 def generate(self, src, dst, **kwargs):
     namespace = self.get_namespace()
     namespace.update(kwargs)
     src_stream = open(src, 'rb')
     template = Template(src_stream.read())
     src_stream.close()
     dst_stream = open(dst, 'wb')
     dst_stream.write(template.substitute(**namespace))
     dst_stream.close()
Пример #5
0
 def get(self, section, option, raw=False, vars=None, _recursion=0):
     value = super(TempitaINIToolsParser, self).get(
         section, option, raw=True, vars=vars, _recursion=_recursion)
     if raw:
         return value
     filename, line_number = self.setting_location(section, option)
     ns = _Namespace(self, section, vars)
     # The -1 is because the first line is line 1, but should have
     # a 0 offset:
     tmpl = Template(value, name=filename, line_offset=line_number-1)
     value = tmpl.substitute(ns)
     return value
Пример #6
0
    def settings_py(self):
        if 'settings-template' in self.options:
            template_fname = self.options['settings-template']
        else:
            template_fname = os.path.join(
                os.path.dirname(__file__),
                'settings.py.in'
            )
        self._logger.debug(
            "Loading settings template from %s" % template_fname
        )
        stream = open(template_fname, 'rb')
        template_definition = stream.read().decode('utf-8')
        stream.close()
        if 'settings-template-extension' in self.options:
            self._logger.debug(
                "Loading settings extension template from %s" % (
                    self.options['settings-template-extension'],
                )
            )
            stream = open(
                self.options['settings-template-extension'],
                'rb'
            )
            template_definition += u"\n\n# Extension template %s\n\n" % (
                self.options['settings-template-extension'],
            )
            template_definition += stream.read().decode('utf-8')
            stream.close()

        variables = {}
        for section in self.buildout.keys():
            variables[section] = bunch(
                **dict(normalize_keys(self.buildout[section]))
            )
        variables.update(dict(normalize_keys(self.options)))
        self.fix_databases(variables)
        variables.update({ 'name': self.name, 'secret': self.secret })
        self._logger.debug(
            "Variable computation terminated:\n%s" % pprint.pformat(variables)
        )
        template = Template(
            template_definition,
            namespace=self._template_namespace
        )
        self._logger.debug(
            "Interpolating template, namespace is:\n%s" % pprint.pformat(
                self._template_namespace
            )
        )
        return template.substitute(variables)
Пример #7
0
 def get(self, section, option, raw=False, vars=None, _recursion=0):
     value = super(TempitaINIToolsParser, self).get(section,
                                                    option,
                                                    raw=True,
                                                    vars=vars,
                                                    _recursion=_recursion)
     if raw:
         return value
     filename, line_number = self.setting_location(section, option)
     ns = _Namespace(self, section, vars)
     # The -1 is because the first line is line 1, but should have
     # a 0 offset:
     tmpl = Template(value, name=filename, line_offset=line_number - 1)
     value = tmpl.substitute(ns)
     return value
Пример #8
0
    def theme(self, environ, start_response):
        req = Request(environ)
        try:
            username = authenticate_from_cookie(req.cookies['__ac'], get_secret(self.secret))[0]
        except:
            username = None
        res = Template("""
<html>
<body>
<div style="background-color: gray">Welcome {{username}}!</div>
<div id="oc-content-container">
</div>
</body>
</html>""")
        res = res.substitute(username=username or "AnonymousUser")
        return Response(res)(environ, start_response)
    def _make_pg_config(self):
        self.log.info("Creating initial PostgreSQL configuration")

        pg_version = self._read_pg_version()

        def template_data(template_name):
            file_name = os.path.join(current_dir, 'templates', template_name)
            return open(file_name).read()

        # Minimal configuration file used to bootstrap the server. Will be
        # replaced with all default values soon after.
        pg_fd = open(os.path.join(self.options['conf-dir'], "postgresql.conf"), 'w')
        pg_fd.write(self.options['postgresql.conf'])

        pghba_tpl = Template(template_data('pg_hba.conf.tmpl'))
        pghba_fd = open(os.path.join(self.options['conf-dir'], "pg_hba.conf"), 'w')
        pghba_fd.write(pghba_tpl.substitute(PG_VERSION=pg_version,
                                            superusers=self.options['superusers'].split(),
                                            users=self.options['users'].split(),
                                            admin=self.options['admin']
                                            ))
Пример #10
0
 def _interpolate(self, section, option, rawval, vars):
     ns = _Namespace(self, section, vars)
     tmpl = Template(rawval, name='%s.%s' % (section, option))
     value = tmpl.substitute(ns)
     return value
Пример #11
0
def rename_process(template: str,
                   files,
                   index_start=1,
                   output_dir=None,
                   regex=None,
                   ignore_missing_regex=False,
                   params={}):
    if regex:
        regex = re.compile(regex)

    if '{plex}' in template:
        template = template.replace('{plex}', PLEX_TEMPLATE)

    if isinstance(params, PlexTemplateParams):
        params = params._asdict()

    length = len(files)
    if 'length' not in params:
        params['length'] = length

    t = Template(content=template,
                 delimiters=('${', '}'),
                 namespace=create_namespace(length))
    results = []

    index = index_start
    for file in files:
        if output_dir:
            dir = output_dir
        else:
            dir = os.path.dirname(file)
        ext = os.path.splitext(file)[1][1::]
        wo_ext = os.path.splitext(file)[0]
        base = os.path.basename(file)
        new_params = {
            'index': index,
            'i': index,
            'wo_ext': wo_ext,
            'ext': ext,
            'filename': base,
            're': RegexResults(ignore_missing=ignore_missing_regex)
        }
        new_params.update(params)
        if regex:
            m = regex.search(base)
            if m:
                items = [m.group()]
                m_index = 1
                for item in m.groups():
                    try:
                        item = int(item)
                    except ValueError:
                        pass
                    items.append(item)
                    m_index += 1
                    new_params['re'] = new_params['regex'] = RegexResults(
                        items, ignore_missing=ignore_missing_regex)
        result = t.substitute(new_params)
        result = os.path.join(dir, result)
        results.append((file, result))
        index += 1

    return results
Пример #12
0
 def template_renderer(self, content, vars, filename=None):
     tmpl = Template(content, name=filename)
     return tmpl.substitute(vars)
Пример #13
0
def plus_filter(s): return "++ " + s + " ++"

context_params = {
    "my_name" : "alice",
    "names" : [ "alice", "bob", "eve" ],
    "people" : [
        { "name" : "alice", "role" : "communicator" },
        { "name" : "bob", "role" : "communicator" },
        { "name" : "eve", "role" : "eavesdropper", "blackhat" : True },
        ],
    "a_bunch" : bunch(a=1,b=2,c=3),
    "plus_filter" : plus_filter,  # Make available as filter
}

print t.substitute(context_params)

print "\nDoing HTML subsitution..."

html_template_string="""
{{# A little counter-intuitive, but use 'html()' to substitute without quotes }}
<a href="{{ target_url | html }}">{{ target_name }}</a>
"""

t2 = HTMLTemplate(html_template_string)

context_params2 = {
    "target_url" : "https://example.com/hello?world&value=2",
    "target_name" : "Here & There",
}
Пример #14
0
 def _interpolate(self, section, option, rawval, vars):
     ns = _Namespace(self, section, vars)
     tmpl = Template(rawval, name='%s.%s' % (section, option))
     value = tmpl.substitute(ns)
     return value
Пример #15
0
 def template_renderer(self, content, vars, filename=None):
     tmpl = Template(content, name=filename)
     return tmpl.substitute(vars)
Пример #16
0
def wmts_capabilities(layers, metadata):
    tmpl = Template(capabilities, namespace={'to_wsg84': to_wsg84})
    return tmpl.substitute(wmts_gettile=metadata.get('wmts_gettile'),
                          layers=layers, matrix_sets=matrix_sets(layers))
Пример #17
0
    def _make_pg_config(self):
        self.log.info("Creating initial PostgreSQL configuration")

        try:
            PG_VERSION = open(os.path.join(self.options['data_dir'],
                                           'PG_VERSION')).read()
        except IOError:
            PG_VERSION = None

        def template_data(template_name):
            file_name = os.path.join(current_dir, 'templates', template_name)
            return open(file_name).read()


        # Minimal configuration file used to bootstrap the server. Will be
        # replaced with all default values soon after.
        pg_tpl = Template(template_data('postgresql.conf.tmpl'))
        pg_fd = open(os.path.join(self.options['data_dir'], "postgresql.conf"),'w')
        pg_fd.write(
            pg_tpl.substitute(
                data_dir = self.options['data_dir'],
                config_dir = self.options['data_dir'],
                pid_file = self.options['pid_file'],
                socket_dir = self.options['socket_dir'],
                listen_addresses = self.options['listen_addresses'],
                unix_socket_directory = self.options['unix_socket_directory'],
                port = self.options['port'],
            ))


        pghba_tpl = Template(template_data('pg_hba.conf.tmpl'))
        pghba_fd = open(os.path.join(self.options['data_dir'], "pg_hba.conf"),'w')
        pghba_fd.write(
            pghba_tpl.substitute(
                PG_VERSION = PG_VERSION,
                superusers = self.options['superusers'].split(),
                users = self.options['users'].split(),
                admin = self.options['admin']
            ))

        # Scripts to be copied into the bin/ directory created by buildout
        buildout_bin_dir = os.path.join(self.buildout["buildout"]["bin-directory"])
        templates = [
            ('pgctl.py.tmpl'     , 'pgctl'),
            ('psql.sh.tmpl'      , 'psql'),
            ('pgctl.py.tmpl'     , 'pgctl'),
            ('createuser.sh.tmpl', 'createuser'),
            ('createdb.sh.tmpl'  , 'createdb'),
        ]

        for template_name, output_name in templates:
            full_output_name = os.path.join(buildout_bin_dir, output_name)

            template = Template(template_data(template_name))
            output = open(full_output_name, 'w')

            output.write(
                template.substitute(
                    bin_dir    = self.options['bin_dir'],
                    socket_dir = self.options['socket_dir'],
                    data_dir   = self.options['data_dir']
                ))

            output.close()
            os.chmod(full_output_name, 0755)