what are most frequently used real-time examples of Django custom middleware? It would be great if a code snippet is also shared.

2

There are 2 best solutions below

1
On

A fairly common piece of Middleware is forcing users to use Https. Here's a snippet:

from django.conf import settings
from django.http import HttpResponsePermanentRedirect


class SSLifyMiddleware(object):
    """Force all requests to use HTTPs. If we get an HTTP request, we'll just
    force a redirect to HTTPs."""

    def process_request(self, request):
        secure_url = url.replace('http://', 'https://')
        return HttpResponsePermanentRedirect(secure_url)
0
On
  1. Handling Authentication/Authorization/Auditing using custom django middleware.
class AuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        header_token = request.META.get('HTTP_AUTHORIZATION', None)
        if header_token is not None:
            header_token = header_token.split() 
            if header_token[0] == "Basic":
                try:
                    token = base64.b64decode(header_token[1]).decode(HTTP_HEADER_ENCODING).partition(':')[0]
                    token_obj = Token.objects.get(key = token)
                    request.user = token_obj.user
                except Token.DoesNotExist:
                    pass
        current_user = getattr(request, 'user', None)
        _do_set_current_user(lambda: current_user)

    def process_response(self, request, response):
        clear_current_user()
        return response
  1. Metrics Instrumentation - To measure response time, throughput, transactions of your application

https://github.com/opentracing-contrib/python-django

  1. Custom CSRF middleware to skip/check on specific requests
from django.middleware.csrf import CsrfViewMiddleware
import codecs

class CustomCsrfMiddleware(CsrfViewMiddleware):
    def process_view(self, request, callback, callback_args, callback_kwargs):
        csrf_skip_header = request.META.get('HTTP_SKIP_CSRF_CHECK')
        if csrf_skip_header # and add your logic here:
                return None
        else:
            return super(CustomCsrfMiddleware, self).process_view(request, callback, callback_args, callback_kwargs)