Python Can';t解析嵌套字符串模板
我使用pymongo来解析mongo查询,我有一个函数,可以接受解析成mongo查询的多个变量。我在模板的safe\u substitute方法上得到了一个错误Python Can';t解析嵌套字符串模板,python,python-2.7,Python,Python 2.7,我使用pymongo来解析mongo查询,我有一个函数,可以接受解析成mongo查询的多个变量。我在模板的safe\u substitute方法上得到了一个错误TypeError:expected string或bytes like object from string import Template from bson.objectid import ObjectId template = Template({"${key}":{"${condition}": ObjectId("${val
TypeError:expected string或bytes like object
from string import Template
from bson.objectid import ObjectId
template = Template({"${key}":{"${condition}": ObjectId("${value}") }})
mongo_filter = template.safe_substitute(key=key, condition='${}'.format(condition), value=value)
基于,方法safe\u substitute
仅接受字符串或类似于对象的字节。在您的情况下,您正在传递与可接受类型不匹配的ObjectId
因此,不能对ObjectId
使用python模板方法
但是,您可以将变量解析为单个变量中的嵌套对象,而无需使用任何库
解决方案
nestedObject = {
key: {
condition: ObjectId(value)
}
}
其中,键
,条件
,值
是要解析为嵌套对象的变量