Django:类型为'datetime'的对象不可JSON序列化 [英] Django: Object of type 'datetime' is not JSON serializable

查看:63
本文介绍了Django:类型为'datetime'的对象不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在会话中保存日期.我总是收到错误类型'datetime'的对象不是JSON可序列化的.我在这里在Django文档中:自日期起存储为秒,因为日期时间无法在JSON中序列化.

I'm trying to save a date in my sessions. I always receive the error Object of type 'datetime' is not JSON serializable. I found this here in the Django documentation: stored as seconds since epoch since datetimes are not serializable in JSON.

如何将 expiry_date 保存为秒而不是日期时间?

How can I save my expiry_date as seconds instead of datetime?

code = social_ticketing_form.cleaned_data['a']
expiry_date = timezone.now() + timezone.timedelta(days=settings.SOCIAL_TICKETING_ATTRIBUTION_WINDOW)
request.session[social_ticketing_cookie_name(request.event)] = {'code': code, 'expiry_date': expiry_date}

推荐答案

Either write your own session serialiser to allow you to serialise datetime objects directly, or store the datetime value in some other form.

如果要将其保存为秒,请使用 datetime.timestamp()方法:

If you want to save it as seconds, then use the datetime.timestamp() method:

request.session[social_ticketing_cookie_name(request.event)] = {
    'code': code, 
    'expiry_date': expiry_date.timestamp()
}

您自己的 SESSION_SERIALIZER 类只需要提供与 json.loads()直接相似的 loads dumps 方法.code>和 json.dumps()(

Your own SESSION_SERIALIZER class only needs to provide loads and dumps methods, directly analogous to json.loads() and json.dumps() (which is how the standard JSON serializer is implemented).

如果您想对 datetime 对象进行编码,并能够再次将它们透明地重新转换为 datetime 对象,则可以使用嵌套对象格式将这些值标记为特殊:

If you want to encode datetime objects and be able to transparently turn those back into datetime objects again, I'd use a nested object format to flag such values as special:

from datetime import datetime

class JSONDateTimeSerializer:
    @staticmethod
    def _default(ob):
        if isinstance(ob, datetime):
            return {'__datetime__': ob.isoformat()}
        raise TypeError(type(ob))

    @staticmethod
    def _object_hook(d):
        if '__datetime__' in d:
            return datetime.fromisoformat(d['__datetime__'])
        return d

    def dumps(self, obj):
        return json.dumps(
            obj, separators=(',', ':'), default=self._default
        ).encode('latin-1')

    def loads(self, data):
        return json.loads(
            data.decode('latin-1'), object_hook=self._object_hook
        )

并将 SESSION_SERIALIZER 设置为上述模块的完整限定名称( path.to.module.JSONDateTimeSerializer ).

and set SESSION_SERIALIZER to the full qualified name of the above module (path.to.module.JSONDateTimeSerializer).

以上内容使用 datetime.fromisoformat()方法,Python 3.7中的新功能.

The above uses the datetime.fromisoformat() method, new in Python 3.7.

这篇关于Django:类型为'datetime'的对象不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆