我有两个服务器在运行,一个运行在python2.7上,另一个运行在python3.8上。
对于这两个服务器,我们都有通用的Django缓存服务器。
python2.7服务器正在Django-cache中设置缓存,python3.8 3.8试图读取此缓存,引发一个错误
"/usr/local/bin/python-3.8.0/lib/python3.8/site-packages/django_redis/serializers/pickle.py",文件行> 35,在加载中返回pickle.loads(值) UnicodeDecodeError:'ascii‘编解码器无法解码位置1中的字节0xe5 :序号不在范围内(128个)
,我已经阅读了下面的文章,并提出了同样的问题
我在这里的目标是能够从python的两个版本读取到通用django缓存。
发布于 2020-01-28 17:47:26
默认的str编码在python 2.7中是ASCII,而3.x的默认编码是utf-8,所以您需要考虑这一点。
如果仔细观察,这不是Redis问题,而是编码问题,因此出现了错误消息:
UnicodeDecodeError:'ascii‘编解码器不能解码字节
要解决这个问题,您必须在python2.7程序中将默认编码设置为utf-8。
import sys
reload(sys)
sys.setdefaultencoding('utf8')这里有关于python编码转换问题的更多详细信息:How to fix UnicodeDecoderError
发布于 2020-01-29 19:18:59
对我有用的解决方案是,我们在redis_cache配置中实现了一个自定义序列化器和加法器。
import six
from django.utils.encoding import force_bytes
from django_redis.serializers.pickle import PickleSerializer
try:
import cPickle as pickle
except ImportError:
import pickle
class CcustomPickleSerializer(PickleSerializer):
def loads(self, value):
if six.PY3:
return self._loads_py3(value)
return super().loads(force_bytes(value))
def _loads_py3(self, value):
return pickle.loads(
force_bytes(value),
fix_imports=True,
encoding='latin1'
)如果将编码方法用作'bytes'。你可以得到字节,否则你会得到一个字符串。
以及下面提到的在cache config中的settings.py行。
'SERIALIZER':'file.location.CustomPickleSerializer'在。
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/0',
'OPTIONS': {
'KEY_PREFIX': 'personify',
'SERIALIZER':'file.location.CustomPickleSerializer',
'PARSER_CLASS': 'redis.connection.HiredisParser', # Hiredis is WAY faster than redis-py
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTION_POOL_KWARGS': {
'max_connections': 100
},
'PICKLE_VERSION': 2, # Make sure we're using v2 of pickle, which is pretty efficient.
'SOCKET_CONNECT_TIMEOUT': 5, # Seconds (timeout for the connection to be established).
'SOCKET_TIMEOUT': 5, # Seconds (timeout for read and write operations after the connection is established).
'IGNORE_EXCEPTIONS': False # Set to True to act like memcached - i.e. don't raise errors.
}
}
}https://stackoverflow.com/questions/59954149
复制相似问题