加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何验证django模板的语法?

发布时间:2020-12-20 13:44:48 所属栏目:Python 来源:网络整理
导读:我希望客户管理员能够编辑他们网站发送的各种状态电子邮件.电子邮件是非常简单的 django模板,存储在数据库中. 我想验证他们没有任何语法错误,缺少变量等,但我无法想出一个简单的方法. 对于未知块标签,它很容易: from django import templatedef render(temp
我希望客户管理员能够编辑他们网站发送的各种状态电子邮件.电子邮件是非常简单的 django模板,存储在数据库中.

我想验证他们没有任何语法错误,缺少变量等,但我无法想出一个简单的方法.

对于未知块标签,它很容易:

from django import template

def render(templ,**args):
    """Convenience function to render a template with `args` as the context.
       The rendered template is normalized to 1 space between 'words'.
    """
    try:
        t = template.Template(templ)
        out_text = t.render(template.Context(args))
        normalized = ' '.join(out_text.split())
    except template.TemplateSyntaxError as e:
        normalized = str(e)
    return normalized

def test_unknown_tag():
    txt = render("""
      a {% b %} c
    """)
    assert txt == "Invalid block tag: 'b'"

我不知道怎么会检测到一个空变量?我知道TEMPLATE_STRING_IF_INVALID设置,但这是一个站点范围的设置.

def test_missing_value():
    txt = render("""
      a {{ b }} c
    """)
    assert txt == "?"

缺少结束标签/值也不会导致任何例外.

def test_missing_close_tag():
    txt = render("""
      a {% b c
    """)
    assert txt == "?"

def test_missing_close_value():
    txt = render("""
      a {{ b c
    """)
    assert txt == "?"

我是否必须从头开始编写解析器来进行基本的语法验证?

解决方法

I don’t know how I would detect an empty variable though?

class CheckContext(template.Context):

    allowed_vars = ['foo','bar','baz']

    def __getitem__(self,k):
        if k in self.allowed_vars:
            return 'something'
        else:
            raise SomeError('bad variable name %s' % k)

missing closing tags/values don’t cause any exceptions either..

您只需检查渲染字符串中是否还有{%,}}等.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读