python3 redis长链接超时_Python3 连接Redis字符串和字节问题探究

前言

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值