Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for doing some specific function. In my case, middleware is used to implement log in and log out features.
The Idea
Log in and Log out can easily be implemented by middleware, although django itself have a powerful part for this named admin
, but we don’t have to do that because it is so power and meantime, complex for beginners.
We can define a middleware function to moniter a fucntion we wrote in views.py
, like login
, and set a cookie to the request package, then we could know whether users are logged in by checking the cookie’s existence.
Django Middleware Mechanism
Create file named
middleware.py
in your project folder:12345mysite/mysite/middleware.pyquery/...
Then all the middlewares you used should be written in this file.
Create login/logout function in views:
1234567891011121314151617181920212223# log in and log outdef login(request):if request.method == 'POST':username = request.POST['username']password = request.POST['password']#print(request.POST)user = User.objects.filter(username__exact = username,password__exact = password)if user:response = HttpResponseRedirect('/query/index')response.set_cookie('username', username, 3600)return responseelse:return HttpResponseRedirect('/query/login/')else:username = Nonepassword = Noneform = {'username': username, 'password': password}return render(request, 'login.html', {'form': form})def logout(request):response = HttpResponseRedirect('/query/login/')response.delete_cookie('username')return responseAs you can see, all you need to do in login/logout functoin is to add or delete cookie, in login function, cookie should pass to back end with request package, and in logout function, delete the cookie.
Middleware function
Let’s see how the Middleware works:
12345678910111213from django.http import HttpResponseRedirectfrom django.utils.deprecation import MiddlewareMixinclass LoginMiddleware(MiddlewareMixin):def process_request(self, request):if request.path != '/query/login/' and 'admin' not in request.path:username = ''if 'username' in request.COOKIES:username = request.COOKIES.get('username')if username != '':passelse :return HttpResponseRedirect('/query/login')You could see that all the path is controlled by url patterns, this is how django works actually. When people visit a http address that is not direct to login page and admin page, web will automatically check the cookie, if cookie exists(request.COOKIES), pass, if not, redirect to the login page.
Register your Middleware
Now you wrote a middleware, but the project doesn’t know its existence, you need to register it in your
settings.py
:12345678910MIDDLEWARE = ['django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware','userlogclient.middleware.LoginMiddleware',]
Finally, run your server and you can see your middleware is working.