Python Pickle 与 Stringify

Python Pickle versus Stringify

目前我正在用 str() 对我的字典进行字符串化,然后将其存储在 redis 中。当我要修改对象时,我从redis中获取它并使用eval()。我看到也可以使用 pickle 模块来做同样的事情。哪个更有效或哪个更好?

obj = # very large and deeply nested dictionary
cache = redis.StrictRedis(host='localhost', port=6379, db=0)
cache.set('id', str(obj))
cache.get('id')

obj = # very large and deeply nested dictionary
cache = redis.StrictRedis(host='localhost', port=6379, db=0)
cache.set('id', pickle.dumps(obj))
pickle.loads(cache.get('id'))

因为你使用的是嵌套字典,而redis只支持

Redis Hashes are maps between string fields and string values

那么使用json模块的最简单方法

import json

your_dict = {}
json.dumps(your_dict)

# and to load it
your_dict_in_str = '{}'
json.loads(your_dict_in_str)

并尽量避免使用eval