Python 到对象的YAML映射
在Python等动态语言中,我知道可以轻松地将YAML映射转换为对象。它可以是一个非常强大的功能,并节省大量的编码 当我尝试将Python 到对象的YAML映射,python,yaml,pyyaml,Python,Yaml,Pyyaml,在Python等动态语言中,我知道可以轻松地将YAML映射转换为对象。它可以是一个非常强大的功能,并节省大量的编码 当我尝试将.yaml文件映射到对象时,遇到了一个问题 文件:objtest.yaml --- test: yaml test option: this is option ... 我的代码: class MyTest(object): pass testObj = MyTest() f = open(os.path.join(os.path.dirnam
.yaml
文件映射到对象时,遇到了一个问题
文件:objtest.yaml
---
test: yaml test
option: this is option
...
我的代码:
class MyTest(object):
pass
testObj = MyTest()
f = open(os.path.join(os.path.dirname(__file__), 'objtest.yaml'))
rawData = yaml.safe_load(f)
print rawData
testObj.__dict__ = yaml.load(f)
f.close()
print testObj
{'test': 'yaml test', 'option': 'this is option'}
Traceback (most recent call last):
File "C:/CROW/ATE/Workspace/Sandbox/test.py", line 23, in <module>
testObj.__dict__ = yaml.load(f)
TypeError: __dict__ must be set to a dictionary, not a 'NoneType'
STDOUT(带回溯):
class MyTest(object):
pass
testObj = MyTest()
f = open(os.path.join(os.path.dirname(__file__), 'objtest.yaml'))
rawData = yaml.safe_load(f)
print rawData
testObj.__dict__ = yaml.load(f)
f.close()
print testObj
{'test': 'yaml test', 'option': 'this is option'}
Traceback (most recent call last):
File "C:/CROW/ATE/Workspace/Sandbox/test.py", line 23, in <module>
testObj.__dict__ = yaml.load(f)
TypeError: __dict__ must be set to a dictionary, not a 'NoneType'
{'test':'yaml test','option':'this is option'}
回溯(最近一次呼叫最后一次):
文件“C:/CROW/ATE/Workspace/Sandbox/test.py”,第23行,在
testObj.\uuuu dict\uuuuuuj=yaml.load(f)
TypeError:\uuuu dict\uuuuuu必须设置为字典,而不是“非类型”
问题:
class MyTest(object):
pass
testObj = MyTest()
f = open(os.path.join(os.path.dirname(__file__), 'objtest.yaml'))
rawData = yaml.safe_load(f)
print rawData
testObj.__dict__ = yaml.load(f)
f.close()
print testObj
{'test': 'yaml test', 'option': 'this is option'}
Traceback (most recent call last):
File "C:/CROW/ATE/Workspace/Sandbox/test.py", line 23, in <module>
testObj.__dict__ = yaml.load(f)
TypeError: __dict__ must be set to a dictionary, not a 'NoneType'
如您所见,该文件已加载到rawData
,但当我尝试将.yaml
文件加载到该类实例时,该类实例testObj
出现问题
知道我做错了什么吗?
rawData=yaml.safe\u load(f)
读取文件,这意味着后面的yaml.load(f)
无法从文件中读取更多数据。虽然您可以倒带seek指针,但绝对没有理由这样做:您已经加载了YAML文档(以一种更安全的方式)。只需执行testObj.\uu dict\uuu=rawData
也就是说,我对分配给
\uuu dict\uuu
有所保留。它可能是实现定义的,也可能不是实现定义的,而且在任何情况下,它都有黑客的味道。零验证、无效数据会导致程序稍后出现类型错误或属性错误(或使用YAML.load
而不是safe\u load
,甚至是任意其他错误,包括静默安全漏洞),而不表示YAML文件有故障。从长远来看,一个合适的序列化库是一个更加健壮和可维护的选择。不确定您到底想做什么。。。看一看关于构造函数、重输入和分解器的部分。如果您确实希望能够加载对象,则需要为其创建SafeRepenter和SafeConstructor。谢谢!它解决了这个问题,关于\uuuu dict\uuuu
我有一个测试YAML有效性的代码,你仍然认为它不安全吗?YAML文件被用作用户必须可读的配置,这就是为什么它比JSON和XML更受欢迎的原因。@KobiK我对YAML没有任何反对意见(我自己使用它),我反对出于上述原因不必要地摆弄\uu dict\uuu
。验证(假设它是正确的)减轻了这些担忧。安全问题与\uuuu dict\uuuu
分配无关,该措辞具有误导性——漏洞利用发生在执行加载过程中。但是对于用户配置,这可能不是一个高优先级的问题。