template.py 文件源码

python
阅读 29 收藏 0 点赞 0 评论 0

项目:birdnet 作者: cyysu 项目源码 文件源码
def compile_templates(root):
    """Compiles templates to python code."""
    re_start = re_compile('^', re.M)

    for dirpath, dirnames, filenames in os.walk(root):
        filenames = [f for f in filenames if not f.startswith('.') and not f.endswith('~') and not f.startswith('__init__.py')]

        out = open(os.path.join(dirpath, '__init__.py'), 'w')
        out.write('from web.template import CompiledTemplate, ForLoop\n\n')
        if dirnames:
            out.write("import " + ", ".join(dirnames))

        for f in filenames:
            path = os.path.join(dirpath, f)

            # create template to make sure it compiles
            t = Template(open(path).read(), path)

            if '.' in f:
                name, _ = f.split('.', 1)
            else:
                name = f

            code = Template.generate_code(open(path).read(), path)
            code = re_start.sub('    ', code)

            _gen = '' + \
            '\ndef %s():' + \
            '\n    loop = ForLoop()' + \
            '\n    _dummy  = CompiledTemplate(lambda: None, "dummy")' + \
            '\n    join_ = _dummy._join' + \
            '\n    escape_ = _dummy._escape' + \
            '\n' + \
            '\n%s' + \
            '\n    return __template__'

            gen_code = _gen % (name, code)
            out.write(gen_code)
            out.write('\n\n')
            out.write('%s = CompiledTemplate(%s(), %s)\n\n' % (name, name, repr(path)))
        out.close()
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号