How to set up custom middleware in Django

故事扮演 提交于 2019-11-26 12:02:22

问题


I am trying to create middleware to optionally pass a kwarg to every view that meets a condition.

The problem is that I cannot find an example of how to set up the middleware. I have seen classes that override the method I want to, process_view:

Class CheckConditionMiddleware(object):  
    def process_view(self, request):  

        return None  

But where do I put this class? Do I create a middleware app and put this class inside of it and then reference it in settings.middleware?


回答1:


First: The path structure

If you don't have it you need to create the middleware folder within your app following the structure:

yourproject/yourapp/middleware

The folder middleware should be placed in the same folder as settings.py, urls, templates...

Important: Don't forget to create the __init__.py empty file inside the middleware folder so your app recognize this folder

Second: Create the middleware

Now we should create a file for our custom middleware, in this example let's supose we want a middleware that filter the users based on their IP, we create a file called filter_ip_middleware.py inside the middleware folder with this code:

class FilterIPMiddleware(object):
    # Check if client IP is allowed
    def process_request(self, request):
        allowed_ips = ['192.168.1.1', '123.123.123.123', etc...] # Authorized ip's
        ip = request.META.get('REMOTE_ADDR') # Get client IP
        if ip not in allowed_ips:
            raise Http403 # If user is not allowed raise Error

       # If IP is allowed we don't do anything
       return None

Third: Add the middleware in our 'settings.py'

We need to look for:

  • MIDDLEWARE_CLASSES (django < 1.10)
  • MIDDLEWARE (django >= 1.10)

Inside the settings.py and there we need to add our middleware (Add it in the last position). It should be like:

MIDDLEWARE = ( #  Before Django 1.10 the setting name was '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',
     # Above are django standard middlewares

     # Now we add here our custom middleware
     'yourapp.middleware.filter_ip_middleware.FilterIPMiddleware'
)

Done ! Now every request from every client will call your custom middleware and process your custom code !




回答2:


Just two steps. It works for me with django2.1.

1.Create your own Middleware class.

There is a good demo from official manual.

https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.get_host

    from django.utils.deprecation import MiddlewareMixin

    class MultipleProxyMiddleware(MiddlewareMixin):
        FORWARDED_FOR_FIELDS = [
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED_HOST',
            'HTTP_X_FORWARDED_SERVER',
        ]

        def process_request(self, request):
            """
            Rewrites the proxy headers so that only the most
            recent proxy is used.
            """
            for field in self.FORWARDED_FOR_FIELDS:
                if field in request.META:
                    if ',' in request.META[field]:
                        parts = request.META[field].split(',')
                        request.META[field] = parts[-1].strip()

2.Reference your Middleware class in the MIDDLEWARE list of your project setting.py file.

The rule for Middleware reference is the path to your class from the root directory of your project.

For example, in a project named mysite,the tree is as follow.

├── mysite
│   ├── manage.py
│   ├── mysite
│   │   ├── __init__.py
│   │   ├── middleware.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py

We just add our Middleware class MultipleProxyMiddleware in the middleware.py file. We get the following reference name.

MIDDLEWARE = [
    'mysite.middleware.MultipleProxyMiddleware',  
     ...
]



回答3:


It will be helpful in the case of When you know what type of Exception occurs in the views. From the above I have Created my own Custom class like

from .models import userDetails

class customMiddleware(object):

    def process_request(self,request):
        result=''
        users = userDetails.objects.all()
        print '-->',users ,'---From middleware calling ---'

        username=request.POST.get("username")
        salary = request.POST.get("salary")
        if salary:
            try:
                result = username+int(salary)
            except:
                print "Can't add"

It will be executed when the exception occur in the case of string and integer addition.

You can write Corresponding views for above middleware class



来源:https://stackoverflow.com/questions/18322262/how-to-set-up-custom-middleware-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!