前言
Python3将逐渐代替Python2,Python2和3还是有很多不同。在开发过程中报了错:
File "/home/hzw/project/test/virtualenv/lib/python3.5/site-packages/test-1.0.0-py3.5.egg/test/templates/wechat_config.js", line 11, in top-level template code
var config = ;
File "/usr/lib/python3.5/json/__init__.py", line 230, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: b'cf43e4f8b6ba463599b616d60cf0683e' is not JSON serializable
数据是缓存在Redis里面的,取出来然后变成一个JSON字符串,但是Python3 bytes类型是无法被串行化为JSON的。需要显示的将bytes转换为字符串,然后才能被串行化。如果每一次从Redis里取出来自己串行化岂不是很麻烦。
本篇将介绍:
Python3和Python2字符串处理的区别;
如何配置Redis处理这种区别,能够让Redis更加透明的工作。
Python2和Python3字符串处理的区别
Python2和Python3字符串处理的区别,可以用six(six是处理Python2和Python3兼容的一个库)里的一段代码来描述:
if PY3:
string_types = str
text_type = str
binary_type = bytes
else:
string_types = basestring
text_type = unicode
binary_type = str
也就是在Python3中不管是普通的字符串还是unicode字符串都是用str这种类型来表示的,而字节类型是用bytes来表示。而在Python2中,字符串的基类是basestring,他有两个子类&#x