python类Template()的实例源码

bottle.py 文件源码 项目:SalesforceXyTools 作者: exiahuang 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def template(*args, **kwargs):
    '''
    Get a rendered template as a string iterator.
    You can use a name, a filename or a template string as first parameter.
    Template rendering arguments can be passed as dictionaries
    or directly (as keyword arguments).
    '''
    tpl = args[0] if args else None
    adapter = kwargs.pop('template_adapter', SimpleTemplate)
    lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
    tplid = (id(lookup), tpl)
    if tplid not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        if isinstance(tpl, adapter):
            TEMPLATES[tplid] = tpl
            if settings: TEMPLATES[tplid].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tplid]:
        abort(500, 'Template (%s) not found' % tpl)
    for dictarg in args[1:]: kwargs.update(dictarg)
    return TEMPLATES[tplid].render(kwargs)
lookup.py 文件源码 项目:pyetje 作者: rorlika 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_template(self, uri):
        """Return a :class:`.Template` object corresponding to the given
        ``uri``.

        .. note:: The ``relativeto`` argument is not supported here at the moment.

        """

        try:
            if self.filesystem_checks:
                return self._check(uri, self._collection[uri])
            else:
                return self._collection[uri]
        except KeyError:
            u = re.sub(r'^\/+', '', uri)
            for dir in self.directories:
                srcfile = posixpath.normpath(posixpath.join(dir, u))
                if os.path.isfile(srcfile):
                    return self._load(srcfile, uri)
            else:
                raise exceptions.TopLevelLookupException(
                                    "Cant locate template for uri %r" % uri)
bottle.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
        """ Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.
        """
        self.name = name
        self.source = source.read() if hasattr(source, 'read') else source
        self.filename = source.filename if hasattr(source, 'filename') else None
        self.lookup = map(os.path.abspath, lookup)
        self.encoding = encoding
        self.settings = self.settings.copy() # Copy from class variable
        self.settings.update(settings) # Apply 
        if not self.source and self.name:
            self.filename = self.search(self.name, self.lookup)
            if not self.filename:
                raise TemplateError('Template %s not found.' % repr(name))
        if not self.source and not self.filename:
            raise TemplateError('No template specified.')
        self.prepare(**self.settings)
bottle.py 文件源码 项目:yt 作者: yt-project 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def template(*args, **kwargs):
    '''
    Get a rendered template as a string iterator.
    You can use a name, a filename or a template string as first parameter.
    Template rendering arguments can be passed as dictionaries
    or directly (as keyword arguments).
    '''
    tpl = args[0] if args else None
    template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
    if tpl not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
        if isinstance(tpl, template_adapter):
            TEMPLATES[tpl] = tpl
            if settings: TEMPLATES[tpl].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tpl]:
        abort(500, 'Template (%s) not found' % tpl)
    for dictarg in args[1:]: kwargs.update(dictarg)
    return TEMPLATES[tpl].render(kwargs)
bottle.py 文件源码 项目:dabdabrevolution 作者: harryparkdotio 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def __exit__(self, exc_type, *_):
        if not self.status: self.status = 'exit'  # silent exit
        self.join()
        return exc_type is not None and issubclass(exc_type, KeyboardInterrupt)

###############################################################################
# Template Adapters ############################################################
###############################################################################
bottle.py 文件源码 项目:dabdabrevolution 作者: harryparkdotio 项目源码 文件源码 阅读 45 收藏 0 点赞 0 评论 0
def __init__(self,
                 source=None,
                 name=None,
                 lookup=None,
                 encoding='utf8', **settings):
        """ Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.
        """
        self.name = name
        self.source = source.read() if hasattr(source, 'read') else source
        self.filename = source.filename if hasattr(source, 'filename') else None
        self.lookup = [os.path.abspath(x) for x in lookup] if lookup else []
        self.encoding = encoding
        self.settings = self.settings.copy()  # Copy from class variable
        self.settings.update(settings)  # Apply
        if not self.source and self.name:
            self.filename = self.search(self.name, self.lookup)
            if not self.filename:
                raise TemplateError('Template %s not found.' % repr(name))
        if not self.source and not self.filename:
            raise TemplateError('No template specified.')
        self.prepare(**self.settings)
bottle.py 文件源码 项目:dabdabrevolution 作者: harryparkdotio 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def prepare(self, **options):
        from mako.template import Template
        from mako.lookup import TemplateLookup
        options.update({'input_encoding': self.encoding})
        options.setdefault('format_exceptions', bool(DEBUG))
        lookup = TemplateLookup(directories=self.lookup, **options)
        if self.source:
            self.tpl = Template(self.source, lookup=lookup, **options)
        else:
            self.tpl = Template(uri=self.name,
                                filename=self.filename,
                                lookup=lookup, **options)
bottle.py 文件源码 项目:dabdabrevolution 作者: harryparkdotio 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def prepare(self, **options):
        from Cheetah.Template import Template
        self.context = threading.local()
        self.context.vars = {}
        options['searchList'] = [self.context.vars]
        if self.source:
            self.tpl = Template(source=self.source, **options)
        else:
            self.tpl = Template(file=self.filename, **options)
bottlim.py 文件源码 项目:anubad-web 作者: foss-np 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def prepare(self, **options):
        from mako.template import Template
        from mako.lookup import TemplateLookup
        from plim import preprocessor
        options.update({'input_encoding':self.encoding})
        options.setdefault('format_exceptions', bool(DEBUG))
        lookup = TemplateLookup(directories=self.lookup, **options)
        if self.source:
            self.tpl = Template(self.source, preprocessor = preprocessor, lookup=lookup, **options)
        else:
            self.tpl = Template(uri=self.name, preprocessor = preprocessor, filename=self.filename, lookup=lookup, **options)
qqhtml.py 文件源码 项目:qqmbr 作者: ischurov 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def handle_align(self, tag: QqTag) -> str:
        """
        Uses tags: align, number, label, item

        Example:
            \align
                \item c^2 &= a^2 + b^2 \label eq:one
                \item c &= \sqrt{a^2 + b^2} \label eq:two

        :param tag:
        :return:
        """

        template = Template(
            r"""\[
\begin{align}
<% items = tag("item") %>
% if items:
% for i, item in enumerate(items):
${formatter.format(item, blanks_to_pars=False)}
% if item.exists("number"):
\tag{${item.number_.value}}
% endif
% if i != len(items):
\\\

% endif
% endfor
% endif
\end{align}
\]
"""
        )
        return template.render(formatter=self, tag=tag)
templates.py 文件源码 项目:kaira 作者: mulonemartin 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __init__(self,
                 source=None,
                 name=None,
                 lookup=None,
                 encoding='utf8', **settings):
        """ Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.
        """
        self.name = name
        self.source = source.read() if hasattr(source, 'read') else source
        self.filename = source.filename if hasattr(source, 'filename') else None
        self.lookup = [os.path.abspath(x) for x in lookup] if lookup else []
        self.encoding = encoding
        self.settings = self.settings.copy()  # Copy from class variable
        self.settings.update(settings)  # Apply
        if not self.source and self.name:
            self.filename = self.search(self.name, self.lookup)
            if not self.filename:
                raise TemplateError('Template %s not found.' % repr(name))
        if not self.source and not self.filename:
            raise TemplateError('No template specified.')
        self.prepare(**self.settings)
templates.py 文件源码 项目:kaira 作者: mulonemartin 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def prepare(self, **options):
        from mako.template import Template
        from mako.lookup import TemplateLookup
        options.update({'input_encoding': self.encoding})
        options.setdefault('format_exceptions', bool(DEBUG))
        lookup = TemplateLookup(directories=self.lookup, **options)
        if self.source:
            self.tpl = Template(self.source, lookup=lookup, **options)
        else:
            self.tpl = Template(uri=self.name,
                                filename=self.filename,
                                lookup=lookup, **options)
templates.py 文件源码 项目:kaira 作者: mulonemartin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def template(*args, **kwargs):
    """
    Get a rendered template as a string iterator.
    You can use a name, a filename or a template string as first parameter.
    Template rendering arguments can be passed as dictionaries
    or directly (as keyword arguments).
    """
    tpl = args[0] if args else None
    for dictarg in args[1:]:
        kwargs.update(dictarg)
    adapter = kwargs.pop('template_adapter', MakoTemplate)
    lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
    tplid = (id(lookup), tpl)
    if tplid not in TEMPLATES or DEBUG:
        settings = kwargs.pop('template_settings', {})
        if isinstance(tpl, adapter):
            TEMPLATES[tplid] = tpl
            if settings: TEMPLATES[tplid].prepare(**settings)
        elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
            TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
        else:
            TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
    if not TEMPLATES[tplid]:
        abort(500, 'Template (%s) not found' % tpl)
    return TEMPLATES[tplid].render(kwargs)


#mako_template = functools.partial(template, template_adapter=MakoTemplate)
imports.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def import_statement(self):
        if self.is_default:
            return Template("""import ${name} from '${path}'""").render(
                name=self.name, path=self.path)
        return Template("""import {${name}} from '${path}'""").render(
            name=self.name, path=self.path)
custom_tab_bar_header.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def update_dependencies(self):
        # No children for CustomTabBarHeader
        from mako.template import Template
        for source_name, source_path in self.icon_source_tuples:
            image_source_dependency = Template(
                """import ${name} from '${path}'""").render(name=source_name,
                                                            path=source_path)
            self.dependencies.add(image_source_dependency)
image.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def update_dependencies(self):
        for child in self.children:
            self.dependencies.add(child.import_statement())
            if not child.is_exportable_component():
                child.update_dependencies()
                self.dependencies.update(child.dependencies)
        from mako.template import Template
        if self.source_name and self.source_path:
            image_source_dependency = Template(
                """import ${name} from '${path}'""").render(
                name=self.source_name,
                path=self.source_path)
            self.dependencies.add(image_source_dependency)
svgcomponent.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def import_statement(self):
        if self.is_default:
            return Template("""import ${name} from '${path}'""").render(
                name=self.layer.name, path=self.path)
        return Template("""import { ${name} } from '${path}'""").render(
            name=self.layer.name, path=self.path)
component.py 文件源码 项目:sketch-components 作者: ibhubs 项目源码 文件源码 阅读 54 收藏 0 点赞 0 评论 0
def import_statement(self):
        if self.is_default:
            return Template("""import ${name} from '${path}'""").render(
                name=self.get_component_name(),
                path=self.get_component_import_path())
        return Template("""import { ${name} } from '${path}'""").render(
            name=self.get_component_name(),
            path=self.get_component_import_path())
template.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def source(self):
        """Return the template source code for this :class:`.Template`."""

        return _get_module_info_from_callable(self.callable_).source
template.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def code(self):
        """Return the module source code for this :class:`.Template`."""

        return _get_module_info_from_callable(self.callable_).code


问题


面经


文章

微信
公众号

扫码关注公众号