Django项目中不正确配置的中间件(导入redis函数时出错)

时间:2016-11-29 11:21:03

标签: django redis middleware

我正在为我的Django应用编写中间件,我从request.session获取变量,然后将其插入到redis排序集中。相当直接。

即。

import os
#os.environ.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings")
from myapp.redis_functions import set_whose_online

class WhoseOnlineMiddleware(object):
    def process_request(self, request):
        if '_auth_user_id' in request.session:
            set_whose_online(request.session['_auth_user_id'])
        else:
            pass

redis_functions.py包含我应用中与redis相关的所有功能。 redis连接池也在那里实例化。

但这会在ImporperlyConfigured给我一个import错误。完整的追溯是:

Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 72, in __call__
    return self.application(environ, start_response)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/dj_static.py", line 83, in __call__
    return self.application(environ, start_response)
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
    self.load_middleware()
  File "/home/myuser/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware
    raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
ImproperlyConfigured: Error importing middleware myproject.middleware.WhoseOnline: "cannot import name add_filtered_post"

令人费解,因为我没有尝试导入add_filtered_post,我试图导入set_whose_onlineadd_filtered_postredis_functions.py中的另一项功能,完全在其他地方使用。

可能会发生什么,我该如何解决这个问题?我猜测循环导入是罪魁祸首,但python manage.py validate --traceback会返回0错误。

这是我settings.py中的内容:

MIDDLEWARE_CLASSES = (
    'myproject.middleware.XForwardedFor.XForwardedForMiddleware',
    'user_sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'myproject.middleware.WhoseOnline.WhoseOnlineMiddleware',
    #'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'myproject.middleware.HellBanned.HellBannedMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'mobileesp.middleware.MobileDetectionMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

注意:中间件是在myfolder/myproject/middleware/WhoseOnline.py添加的,即与settings.py,urls,templates相同的文件夹

1 个答案:

答案 0 :(得分:0)

虽然可能有多种原因发生,但在我的特殊情况下,这是因为循环导入。我诊断并解决了这个问题,然后就消失了。