使用自定义双括号格式的Python模板安全替换

我正在尝试用Python的模板替换{{var}}格式的变量.

# -*- coding: utf-8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4

from string import Template
class CustomTemplate(Template):
    delimiter = '{{'
    pattern = r'''
    \{\{(?:
    (?P<escaped>\{\{)|
    (?P<named>[_a-z][_a-z0-9]*)\}\}|
    (?P<braced>[_a-z][_a-z0-9]*)\}\}|
    (?P<invalid>)
    )
    '''

replacement_dict = {
    "test": "hello"
}

tpl = '''{
    "unaltered": "{{foo}}",
    "replaced": "{{test}}"
}'''

a = CustomTemplate(tpl)
b = a.safe_substitute(replacement_dict)

print b

输出:

{
    "unaltered": "{{foo",
    "replaced": "hello"
}

如您所见,{{foo}}变量(不属于替换变量)的右括号被切掉.

我认为这是正则表达式的编写方式(}}的结尾).
我想使用模板而不是任何其他外部库来解决此问题.

解决方法:

我不确定您是怎么做到的.在linux上,在python 3.4.3中(我以为我可以在2.7的某个版本上使用它)我需要使tpl成为字符串

tpl = '''
    "unaltered": "{{foo}}",
    "replaced": "{{test}}"
'''

避免出现TypeError

>>> tpl = '''
...     "unaltered": "{{foo}}",
...     "replaced": "{{test}}"
... '''
>>> a = CustomTemplate(tpl)
>>> a.template
'\n    "unaltered": "{{foo}}",\n    "replaced": "{{test}}"\n'
>>> b = a.safe_substitute(replacement_dict)
>>> b
'\n    "unaltered": "{{foo}}",\n    "replaced": "hello"\n'

当我这样做时,{{foo}}保持不变.

我尝试了上面的代码,看起来该代码实际上不适用于python 2.7.6.我将看看是否可以找到一种使其与2.7.6一起工作的方法,因为这似乎是最近的Linux发行版的常见版本.

更新:

看来这是2007年以来的已知错误.据我所知,http://bugs.python.org/issue1686它已在2010年应用于python 3.2,在2014年应用于python 2.7.要使其正常工作,您可以应用问题1686的补丁,也可以使用此补丁https://hg.python.org/cpython/file/8a98ee6baa1e/Lib/string.py中的实际源代码覆盖类中的safe_substitute().

该代码在2.7.6和3.4.3中有效

from string import Template
class CustomTemplate(Template):
    delimiter = '{{'
    pattern = r'''
    \{\{(?:
    (?P<escaped>\{\{)|
    (?P<named>[_a-z][_a-z0-9]*)\}\}|
    (?P<braced>[_a-z][_a-z0-9]*)\}\}|
    (?P<invalid>)
    )
    '''

    def safe_substitute(self, *args, **kws):
        if len(args) > 1:
            raise TypeError('Too many positional arguments')
        if not args:
            mapping = kws
        elif kws:
            mapping = _multimap(kws, args[0])
        else:
            mapping = args[0]
        # Helper function for .sub()
        def convert(mo):
            named = mo.group('named') or mo.group('braced')
            if named is not None:
                try:
                    # We use this idiom instead of str() because the latter
                    # will fail if val is a Unicode containing non-ASCII
                    return '%s' % (mapping[named],)
                except KeyError:
                    return mo.group()
            if mo.group('escaped') is not None:
                return self.delimiter
            if mo.group('invalid') is not None:
                return mo.group()
            raise ValueError('Unrecognized named group in pattern',
                             self.pattern)
        return self.pattern.sub(convert, self.template)

replacement_dict = {
    "test": "hello"
}

tpl = '''{
    "escaped": "{{{{",
    "unaltered": "{{foo}}",
    "replaced": "{{test}}",
    "invalid": "{{az"
}'''

a = CustomTemplate(tpl)
b = a.safe_substitute(replacement_dict)

print (b)

结果:

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import template
{
    "escaped": "{{",
    "unaltered": "{{foo}}",
    "replaced": "hello",
    "invalid": "{{az"
}
>>> 
上一篇:从Java对象类到C


下一篇:java-如何使用#{field’variable’}