Web Project Using Django: Middleware

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

  1. Create file named middleware.py in your project folder:

    1
    2
    3
    4
    5
    mysite/
    mysite/
    middleware.py
    query/
    ...

Then all the middlewares you used should be written in this file.

  1. Create login/logout function in views:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    # log in and log out
    def 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 response
    else:
    return HttpResponseRedirect('/query/login/')
    else:
    username = None
    password = None
    form = {'username': username, 'password': password}
    return render(request, 'login.html', {'form': form})
    def logout(request):
    response = HttpResponseRedirect('/query/login/')
    response.delete_cookie('username')
    return response

    As 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.

  2. Middleware function

    Let’s see how the Middleware works:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    from django.http import HttpResponseRedirect
    from django.utils.deprecation import MiddlewareMixin
    class 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 != '':
    pass
    else :
    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.

  3. 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:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    MIDDLEWARE = [
    '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.