11

我有一个 django 应用程序,它在1.4.2版本上运行并且工作完全正常,但最近我将它更新到 django1.6.5并面临一些奇怪的错误,如下所示

实际上,我在我的网站功能中的用户/客户端注册过程中得到了这个

Request URL:    http://example.com/client/registration/
Django Version:     1.6.5
Exception Type:     TypeError
Exception Value:    <Client: test one> is not JSON serializable
Exception Location:     /usr/lib/python2.7/json/encoder.py in default, line 184
Python Executable:  /home/user/.virtualenvs/test_proj/bin/python
Python Version:     2.7.5

追溯

Traceback:
File "/home/user/.virtualenvs/test_proj/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  199.                 response = middleware_method(request, response)
File "/home/user/.virtualenvs/test_proj/local/lib/python2.7/site-packages/django/contrib/sessions/middleware.py" in process_response
  38.                     request.session.save()
File "/home/user/.virtualenvs/test_proj/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in save
  57.             session_data=self.encode(self._get_session(no_load=must_create)),
File "/home/user/.virtualenvs/test_proj/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in encode
  87.         serialized = self.serializer().dumps(session_dict)
File "/home/user/.virtualenvs/test_proj/local/lib/python2.7/site-packages/django/core/signing.py" in dumps
  88.         return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/lib/python2.7/json/__init__.py" in dumps
  250.         sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py" in encode
  207.         chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py" in iterencode
  270.         return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py" in default
  184.         raise TypeError(repr(o) + " is not JSON serializable")

Exception Type: TypeError at /client/registration/
Exception Value: <Client: test one> is not JSON serializable

我对为什么更新后出现上述 json 错误以及我在一些模型中使用自定义 json 字段的方式感到困惑,如下所示

项目/utils.py

from django.db import models
from django.utils import simplejson as json
from django.core.serializers.json import DjangoJSONEncoder


class JSONField(models.TextField):
    '''JSONField is a generic textfield that neatly serializes/unserializes
    JSON objects seamlessly'''

    # Used so to_python() is called
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        '''Convert our string value to JSON after we load it from the DB'''
        if value == '':
            return None
        try:
            if isinstance(value, basestring):
                return json.loads(value)
        except ValueError:
            pass
        return value

    def get_db_prep_save(self, value, connection=None):
        '''Convert our JSON object to a string before we save'''
        if not value or value == '':
            return None
        if isinstance(value, (dict, list)):
            value = json.dumps(value, mimetype="application/json")
        return super(JSONField, self).get_db_prep_save(value, connection=connection)

from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^proj\.util\.jsonfield\.JSONField"])

设置.py

SERIALIZATION_MODULES = {
     'custom_json': 'proj.util.json_serializer',
        }

json_serializer.py

from django.core.serializers.json import Serializer as JSONSerializer
from django.utils.encoding import is_protected_type

# JSONFields that are normally incorrectly serialized as strings
json_fields = ['field_1', 'field_2']


class Serializer(JSONSerializer):
    """
    A fix on JSONSerializer in order to prevent stringifying JSONField data.
    """
    def handle_field(self, obj, field):
        value = field._get_val_from_obj(obj)
        # Protected types (i.e., primitives like None, numbers, dates,
        # and Decimals) are passed through as is. All other values are
        # converted to string first.
        if is_protected_type(value) or field.name in json_fields:
            self._current[field.name] = value
        else:
            self._current[field.name] = field.value_to_string(obj)

那么如何解决上述错误呢?有人可以解释导致错误的原因吗?

4

3 回答 3

46

Django 1.6 将序列化程序从 pickle 更改为 json。pickle 可以序列化 json 不能序列化的东西。

您可以更改SESSION_SERIALIZER的值settings.py以从 Django 1.6 之前的版本中恢复行为。

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

您可能想在文档中阅读有关会话序列化的信息。

于 2014-06-15T20:21:30.003 回答
6

将此行设置为 settings.py 将在升级到 django 1.6 版本时清除错误

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
于 2014-06-16T09:27:20.180 回答
1

分析回溯后,似乎 JSONEncoder 无法序列化您的Client模型的实例。通常,如果您尝试使用jsonsimplejson库序列化与其他模型(Many2ManyField 等)相关的模型,则会出现此类错误。

看这个https://docs.djangoproject.com/en/dev/topics/serialization/,你还可以根据需要使用一些 3rd-party 包,例如DjangoRestFramework

于 2014-06-15T12:20:00.160 回答