You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django中如何正确设置与获取字典或列表类型的Cookie?

在Django中正确设置和获取字典/列表类型Cookie的方法

问题原因

Cookie本质上只能存储字符串类型的数据。你直接将字典、列表存入Cookie时,Django会自动把它们转为字符串形式,但读取时不会自动反序列化为原数据类型,所以会出现无法通过键或索引访问内容的错误(比如把列表字符串当成普通字符串取索引得到的是单个字符)。

解决方案:用JSON序列化/反序列化

通过JSON将字典、列表转为字符串存入Cookie,读取时再将字符串转回原数据类型即可。

1. 设置Cookie(序列化字典/列表)

# views.py
from django.http import HttpResponse
import json

def set_cookie_view(request):
    response = HttpResponse('Cookie已设置')
    
    # 序列化字典并存入Cookie
    teacher_dict = {'name': 'John', 'age': 36}
    response.set_cookie('teacher', json.dumps(teacher_dict))
    
    # 序列化列表并存入Cookie
    student_list = ['David', 21]
    response.set_cookie('student', json.dumps(student_list))
    
    return response

2. 获取Cookie(反序列化回字典/列表)

# views.py
from django.http import HttpResponse
import json

def get_cookie_view(request):
    # 读取并反序列化字典类型Cookie
    teacher_str = request.COOKIES.get('teacher')
    if teacher_str:
        teacher_dict = json.loads(teacher_str)
        print(teacher_dict['name'])  # 输出 John
        print(teacher_dict['age'])   # 输出 36
    
    # 读取并反序列化列表类型Cookie
    student_str = request.COOKIES.get('student')
    if student_str:
        student_list = json.loads(student_str)
        print(student_list[0])  # 输出 David
        print(student_list[1])  # 输出 21
    
    return HttpResponse('Cookie已读取')

注意事项

  • 必须导入json模块,用于完成序列化和反序列化操作。
  • Cookie有大小限制(通常不超过4KB),避免存储过大的数据。
  • 若需存储敏感数据,建议先加密再存入Cookie,防止数据泄露。

内容的提问来源于stack exchange,提问作者Super Kai - Kazuya Ito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 02:33:09