separators=separators
File "/usr/local/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/local/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/usr/local/lib/python2.7/site-packages/djangorestframework-3.3.3-py2.7.egg/rest_framework/utils/encoders.py", line 64, in default
return super(JSONEncoder, self).default(obj)
File "/usr/local/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: OSError(2, 'No such file or directory') is not JSON serializable
今天遇到一个很好玩的bug,接口程序报错如上,报错原因是数据的类型错误,导致接口无法进行序列化,这个错误数据的类型是OSError,奇怪的是程序里没有引用过这个东西。
原因:
排查接口发现,程序里使用了eval() 函数,这个函数强大而可怕,它把字符串类型的字典值OSError(2, 'No such file or directory')
变成了对象(python 内建对象)类型的字典值,这个值是不能被序列化的,故导致了报错。
解决:
直接把eval()后的字典值强转成string类型,即可完成序列化。
注意:
eval() 方法还是少用,会引起系统漏洞的概率很大。