django中simplesjon的一个traceback

今天在跑代码的时候发现一个异常,如图:

TypeError: __init__() got an unexpected keyword argument 'namedtuple_as_object'

这个问题在django官方文档里有交代过,参考链接:https://docs.djangoproject.com/en/dev/releases/1.5/#system-version-of-simplejson-no-longer-used

There are no known incompatibilities between Django’s copy of version 2.0.7 and Python’s copy of version 2.0.9. However, there are some incompatibilities between other versions of simplejson:

  • While the simplejson API is documented as always returning unicode strings, the optional C implementation can return a byte string. This was fixed in Python 2.7.
  • simplejson.JSONEncoder gained a namedtuple_as_object keyword argument in version 2.2.

 

同时,也可以查看一下django.utils.simplejson.py源码:

 1 # Django 1.5 only supports Python >= 2.6, where the standard library includes
 2 # the json module. Previous version of Django shipped a copy for Python < 2.6.
 3 
 4 # For backwards compatibility, we're keeping an importable json module
 5 # at this location, with the same lookup sequence.
 6 
 7 # Avoid shadowing the simplejson module
 8 from __future__ import absolute_import
 9 
10 import warnings
11 warnings.warn("django.utils.simplejson is deprecated; use json instead.",
12               PendingDeprecationWarning)
13 
14 try:
15     import simplejson
16 except ImportError:
17     use_simplejson = False
18 else:
19     # The system-installed version has priority providing it is either not an
20     # earlier version or it contains the C speedups.
21     from json import __version__ as stdlib_json_version
22     use_simplejson = (hasattr(simplejson, '_speedups') or
23         simplejson.__version__.split('.') >= stdlib_json_version.split('.'))
24 
25 # Make sure we copy over the version. See #17071
26 if use_simplejson:
27     from simplejson import *
28     from simplejson import __version__
29 else:
30     from json import *
31     from json import __version__

 我是一开始是根据源码里的方法来比较simplejson的版本号,因为文档中说,版本号为2.0.7,2.0.9没有发生不兼容的现象

于是我删除了python自带的simplejson:

1 mv /usr/local/lib/python2.7/dist-packages/simplejson* ~/

用pip安装了2.0.9版本的simplejson:

1 pip install simplejson==2.0.9

bingo!异常消除了。

其实还有更简单的办法,通过django源码看出,没有simplejson会用json,所以,直接移除更简单!但是这样以后你本地的python库就没有simplejson用了。。。

看自己怎么取舍吧。

我这里的环境是:

1 Django=1.5.5
2 Python=2.7.5+
3 simplejson=3.3.0

 

TypeError: __init__() got an unexpected keyword argument 'namedtuple_as_object'

posted @ 2014-04-01 16:40  张小泉  Views(564)  Comments(0)    收藏  举报