python __proxy__ is not JSON serializable

2019-06-18 发表在 编程语言 573

详细错误如下

TypeError at /
Object of type __proxy__ is not JSON serializable
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 2.2.2
Exception Type: TypeError
Exception Value:    
Object of type __proxy__ is not JSON serializable
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py in default, line 179
Python Executable:  /Users/panjing/PycharmProjects/simpleui_demo/venv/bin/python
Python Version: 3.7.1
Python Path:    
['/Users/panjing/PycharmProjects/simpleui_demo',
 '/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Users/panjing/PycharmProjects/simpleui_demo',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_display',
 '/Applications/PyCharm.app/Contents/helpers/third_party/thriftpy',
 '/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Users/panjing/Library/Caches/PyCharm2019.1/cythonExtensions',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/setuptools-39.1.0-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/xadmin-0.6.1-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/six-1.12.0-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/future-0.17.1-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/django_reversion-3.0.4-py3.7.egg',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf']

原因 对象是Promise,所以直接json序列话会报错

加一个自定义的解码类就可以了

from django.utils.functional import Promise
from django.core.serializers.json import DjangoJSONEncoder

class LazyEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_text(obj)
        return super(LazyEncoder, self).default(obj)


json.dumps(data,cls=DjangoJSONEncoder)      

参考资料

作者:贝塔博客
本站使用「署名 4.0 国际」创作共享协议,转载请在文章明显位置注明作者及出处。
评论
登录以后才可以发布评论哦, 点击登录 发布评论
评论列表 0人参与,0条评论
暂时还没有人评论,快来一条神回复吧!