如何解决ImportError:无法在Django中导入名称simplejson

Sun*_*Lee 12 python django json simplejson django-1.7

我正在尝试在Django(1.7.1)中构建一个实时聊天应用程序.看来我需要安装Redis和ishout.js.所以我按照说明安装了它们.

在Django中创建项目后,我将'drealtime'放在INSTALLED_APPS下,然后放入:

'drealtime.middleware.iShoutCookieMiddleware' 
Run Code Online (Sandbox Code Playgroud)

正上方 :

'django.contrib.sessions.middleware.SessionMiddleware' 
Run Code Online (Sandbox Code Playgroud)

下的MIDDLEWARE_CLASSES,因为它在说什么.我把命令就像

python manage.py startapp example
Run Code Online (Sandbox Code Playgroud)

但我仍然有这个导入错误消息:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
    django.setup()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/config.py", line 87, in create
    module = import_module(entry)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/drealtime/__init__.py", line 4, in <module>
    from django.utils import simplejson as json
Run Code Online (Sandbox Code Playgroud)

在我搜索了Django官方网站后,我发现simplejson已不再使用并从新的Django中移除.我不知道为什么会这样.请提供有关此问题的任何反馈以及解决此问题的可能补救措施.

ale*_*cxe 14

您正在使用过时的版本django-realtime.

将其升级到最新版本,他们修复了1.7兼容性:

pip install django-realtime --upgrade
Run Code Online (Sandbox Code Playgroud)

如果错误仍然存​​在,请直接从github,master分支安装:

$ pip install git+https://github.com/anishmenon/django-realtime.git --upgrade
Run Code Online (Sandbox Code Playgroud)

仅供参考,修复:

try:
    from django.utils import simplejson as json
except:
    import simplejson as json
Run Code Online (Sandbox Code Playgroud)

裸例外条款-禅程序员里面是杀害我低语except ImportError,except ImportError,除..


小智 5

我认为以上答案是解决方法.

Django曾经在django.utils发布simplejson,但是在Django 1.5中删除了它,因为json模块在Python的标准库中可用.

因此,您现在应该import json代替from django.utils import simplejson,并在调用simplejson方法时进行必要的更改.