运行python 2.7 Django 1.6这是我的代码:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'gest.middleware.RequireLoginMiddleware',
'gest.NeedCnd.NeedCndSelectedMiddleware',
'gest.NeedEf.NeedEfSelectedMiddleware',
)
NEED_CND_URLS= (
r'/tab/(.*)$',
r'/ric/(.*)$',
r'/prev/(.*)$',
r'/ese/(.*)$',
)
NEED_EF_URLS= (
r'/ric/(.*)$',
r'/prev/(.*)$',
)
LOGIN_REQUIRED_URLS = (
r'/cnd/(.*)$',
r'/cap/(.*)$',
r'/tab/(.*)$',
r'/ric/(.*)$',
r'/prev/(.*)$',
r'/ese/(.*)$',
)
#this is my NeedEf.py
## -*- coding: iso-8859-1 -*-
import re
from django.shortcuts import render_to_response
from django.conf import settings
from django.template import RequestContext
class NeedEfSelected(object):
def __init__(self, orig_func):
self.orig_func = orig_func
def __call__(self, request, *args, **kwargs):
if request.session.get('sel_esercizio',9999) != 9999:
return self.orig_func(request, *args, **kwargs)
else:
mess=" e\' necessario selezionare prima un esercizio;"
d= {'mess': mess, 'redir':'/ese/', 'class':'wrn'}
return render_to_response('generic_mess.html',d,
context_instance=RequestContext(request))
class NeedEfSelectedMiddleware(object):
def __init__(self):
self.required = tuple([re.compile(url) for url in settings.NEED_EF_URLS])
def process_view(self,request,view_func,view_args,view_kwargs):
# No need to process URLs if user already logged in
for url in self.required:
if url.match(request.path):
return NeedEfSelected(view_func)(request,*view_args,**view_kwargs)
return None
当我访问mysite.net/prev/或mysite.net/ric/时,url.match(request.path)结果为False,因此不会调用NeedEfSelected。任何帮助将不胜感激。
雅皮士!我解决了自己!我被误解了。这个中间件之前是另一个。像这样的第一个有一个错误: 返回self.orig_func(请求,* args,** kwargs)
应替换为返回无
因为中间件的逻辑可以使用。实际上,中间件按顺序执行,当所有测试通过时,返回None ,或者当您需要修改调用的url的正常执行时, HttpResponse 。它得到了很好的解释 https://docs.djangoproject.com/en/dev/topics/http/middleware/ 但我很快就冲浪了