Cheetah3中'request'为保留字,如何在模板中使用该字典变量?
Cheetah3 保留字冲突的解决办法(无需修改XML根元素)
问题场景
我使用Cheetah3作为模板引擎转换XML格式,原本基于<example>根元素的XML和对应Python代码可正常运行:
原XML示例
<?xml version="1.0" encoding="UTF-8"?> <example code="HI"> <codes> <code>1</code> <code>2</code> </codes> </example>
原Python代码
#!/usr/bin/env python import xmltodict from Cheetah.Template import Template with open('example.xml', 'r') as f: example_xml = f.read() example_dict = xmltodict.parse(example_xml) templateDefinition = "This is a template.\n" \ "Example: $example\n" \ "Example: $example.codes\n" \ "Example: $example.codes.code[0]" template = Template(templateDefinition, searchList=[example_dict]) print(str(template))
将XML根元素改为<request>,并把模板中的$example替换为$request后程序报错,原因是request是Cheetah3的保留字,现寻求无需修改XML根元素的解决办法。
可行解决方案
1. 给解析结果套一层字典包装
修改Python代码,将xmltodict解析后的字典放入一个新字典中,用非保留字作为外层键,模板通过这个键访问request数据:
#!/usr/bin/env python import xmltodict from Cheetah.Template import Template with open('example.xml', 'r') as f: example_xml = f.read() example_dict = xmltodict.parse(example_xml) # 用非保留字包裹原字典 wrapped_data = {"data": example_dict} # 模板中通过$data.request访问目标数据 templateDefinition = "This is a template.\n" \ "Example: $data.request\n" \ "Example: $data.request.codes\n" \ "Example: $data.request.codes.code[0]" template = Template(templateDefinition, searchList=[wrapped_data]) print(str(template))
2. 使用Cheetah内置的$getVar()方法
无需修改字典结构,直接在模板中通过$getVar('request')访问保留字对应的变量,绕过保留字限制:
#!/usr/bin/env python import xmltodict from Cheetah.Template import Template with open('example.xml', 'r') as f: example_xml = f.read() example_dict = xmltodict.parse(example_xml) # 模板中用getVar方法获取保留字变量 templateDefinition = "This is a template.\n" \ "Example: $getVar('request')\n" \ "Example: $getVar('request').codes\n" \ "Example: $getVar('request').codes.code[0]" template = Template(templateDefinition, searchList=[example_dict]) print(str(template))
3. 移除Cheetah的保留字(不推荐)
通过修改Cheetah编译器的全局保留字集合移除request,但此操作是全局生效的,可能破坏Cheetah原有功能,需谨慎使用:
#!/usr/bin/env python import xmltodict from Cheetah.Template import Template from Cheetah.Compiler import Compiler # 全局移除request保留字 Compiler.reservedWords.discard('request') with open('example.xml', 'r') as f: example_xml = f.read() example_dict = xmltodict.parse(example_xml) # 模板可直接使用$request templateDefinition = "This is a template.\n" \ "Example: $request\n" \ "Example: $request.codes\n" \ "Example: $request.codes.code[0]" template = Template(templateDefinition, searchList=[example_dict]) print(str(template))
内容的提问来源于stack exchange,提问作者Cynan
相关产品推荐
相关产品推荐

