django 缓存统计在线人数,自写中间件总是提示:'ZxMiddleware' object is not callable

middle.py

from django.core.cache import cache


class ZxMiddleware(object):
    def __init__(self, values):
        self.online_ips = values
        
    # def __call__(self, request):
        # pass
        
    def process_request(self, request):
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['REMOTE_ADDR']
        online_ips = cache.get("online_ips", [])
        if online_ips:
            online_ips = cache.get_many(online_ips).keys()
        cache.set(ip, 0, 15 * 60)
        if ip not in online_ips:
            online_ips.append(ip)
        cache.set("online_ips", online_ips)

在settings.py里

MIDDLEWARE = (
    ...其它的中间件
    'appb.middle.ZxMiddleware',
    
)

views.py 这里用

def get_online_count():
    online_ips = cache.get("online_ips", [])
    if online_ips:
        online_ips = cache.get_many(online_ips).keys()
        return len(online_ips)
    return 0

总是提示:

Traceback:

File "E:\python27\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

Exception Type: TypeError at /
Exception Value: 'ZxMiddleware' object is not callable

clipboard.png

不知哪里有错?

阅读 4.5k
2 个回答

settings配置MIDDLEWARE_CLASSES,看你这里写的不对
另外你的__init__的values是干啥用的,在启用middleware的时候你在哪有传值?

__init__ 去了,将 self.online_ips = get_online_count() 放到 process_request 中,每次请求都得获取一次在线人数

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题