如何在 django 缓存中保存数组



我在 django 缓存中保存数组时遇到了问题。当我从 django 缓存中检索数组 [['hello',1],[2,3]] 时,它会转换为 [['hello', 1] , [2, 3]]。本质上,单引号更改为 ascii 字符代码。简单字符串不会发生此问题。如何避免此问题?

s = [['hello',1],[2,3]]
    s1 = json.dumps(s)
    cache.set('testv',s1)
    a = json.loads(cache.get('testv'))
    return render(request,'sm/technical_tt.html',{'start':a})

这只能是相同的简单string不能object所以你需要dump arraystring进行保存和访问,只需load stringarray Ex:

import json
arr = [['hello',1],[2,3]]
arr = json.dumps(arr)
# Here you can save 'arr' var in cache and it'll save as
# Output => arr = '[["hello", 1], [2, 3]]'
arr = '[["hello", 1], [2, 3]]'
arr = json.loads(arr)
# Output => arr = [["hello", 1], [2, 3]]

最新更新