django 缓存统计在线人数,自写中间件总是提示:'ZxMiddleware' object is not callable
middle.py
from django.core.cache import cacheclass 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
不知哪里有错?
回答:
settings配置MIDDLEWARE_CLASSES,看你这里写的不对
另外你的__init__的values是干啥用的,在启用middleware的时候你在哪有传值?
回答:
把 __init__
去了,将 self.online_ips = get_online_count()
放到 process_request 中,每次请求都得获取一次在线人数
以上是 django 缓存统计在线人数,自写中间件总是提示:'ZxMiddleware' object is not callable 的全部内容, 来源链接: utcz.com/a/157833.html