我有一个简单的字典,我正试图保存到缓存中,看起来像是django正在试图腌制它:
podcasts = []
for i in items:
s = re.sub('[\s+]', '', str(i))
s2 = re.findall(r'<link/>(.*?)<itunes',s)[0]
item_obj = {}
item_obj['title'] = title
item_obj['url'] = s2
item_obj['created_at'] = created_at
item_obj['duration'] = duration
podcasts.append(item_obj)它有一个非常简单的格式,输出如下:
[{'title': "Podcast1", 'url': 'https://example.com\\n', 'created_at': 'Thu, 28 Dec 2017', 'duration': '00:30:34'}]我从一个自定义管理命令运行此命令,如下所示:
python3 manage.py podcast_job我尝试保存到缓存:
podcasts = get_podcasts()
print(podcasts)
cache.set('podcasts', podcasts)我得到了错误:
File "podcast_job.py", line 13, in handle
cache.set('podcasts', podcasts)
File "python3.6/site-packages/django_redis/cache.py", line 33, in _decorator
return method(self, *args, **kwargs)
File "python3.6/site-packages/django_redis/cache.py", line 68, in set
return self.client.set(*args, **kwargs)
File "python3.6/site-packages/django_redis/client/default.py", line 109, in set
nvalue = self.encode(value)
File "python3.6/site-packages/django_redis/client/default.py", line 329, in encode
value = self._serializer.dumps(value)
File "python3.6/site-packages/django_redis/serializers/pickle.py", line 33, in dumps
return pickle.dumps(value, self._pickle_version)
RecursionError: maximum recursion depth exceeded while calling a Python object 如果我尝试用一个字符串保存,我没有得到任何错误,它保存得很好:
cache.set('podcasts', str(podcasts))如何保存字典列表而不出现上述错误?
发布于 2018-01-06 04:14:23
如果对created_at和duration使用datetime对象,请确保将它们呈现为字符串。
发布于 2018-01-06 04:14:00
Pickle不能很好地处理函数。
请查看以下答案以获得一些见解:https://stackoverflow.com/a/1253813/4225229
您可以序列化函数的结果(尝试使用json.dumps())并对其进行缓存。
发布于 2018-01-06 06:04:07
我按照雅各布的建议用json转换了字典,如下所示:
cache.set('podcasts', json.dumps(podcasts))https://stackoverflow.com/questions/48120570
复制相似问题