我正在编写一种通过将中间件写入文件来跟踪用户活动的中间件;他访问过的页面,单击的按钮等等。现在要测试我的中间件,我只是向文件中写入一条消息。但是由于某种原因,消息被两次写入文件。我在Django 1.11上
这是我的中间件:
from django.http import HttpResponse
import datetime
class TodoappMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
f = open("--my file path--", 'a')
date_and_time = datetime.datetime.now()
f.write('\n')
f.write(str(date_and_time))
f.write('\tMiddleware successfully executed\n')
f.close()
response = self.get_response(request)
return response
编辑:了解重定向导致中间件执行两次。
这是我使用HttpResponseRedirect
def login_user(request):
if request.method == 'POST':
login_form = Login(request.POST)
if login_form.is_valid():
email = login_form.cleaned_data['email']
password = login_form.cleaned_data['password']
User.objects.get(email=email)
user = authenticate(email=email, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse('dashboard'))
else:
return HttpResponse("<h2>Waiting for admin to authenticate you</h2>")
else:
return render(request, 'registration/login.html', {'errors': login_form.errors})
return render(request, 'registration/login.html', {'form': Login()})
@login_required
def logout_user(request):
logout(request)
return redirect('login_user')
我需要做些什么更改才能使中间件只执行一次?