如何在django中设置自定义中间件 [英] how to setup custom middleware in django

查看:165
本文介绍了如何在django中设置自定义中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建中间件,以便可以将kwarg传递给符合条件的每个视图。

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

问题是我找不到如何设置的示例中间件我看过类覆盖我想要的方法,process_view:

The problem is that I cannot find an example of how to setup 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  

但是我在哪里这个班?我创建一个中间件应用程序并将此类放在它中,然后在settings.middleware中引用它?

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 the settings.middleware ?

推荐答案

路径结构



如果没有,您需要根据以下结构在应用程序中创建中间件文件夹:

yourproject/yourapp/middleware

文件夹中间件应该放在与settings.py,urls,templates ...相同的文件夹中。

重要提示:请勿忘记在中间件文件夹中创建__init__.py空文件,以便您的应用程序识别此文件夹

现在我们应该为自定义中间件创建一个文件,在这个例子中,我们假设我们想要一个基于IP过滤用户的中间件,我们创建一个名为 filter_ip_middleware.py 中间件文件夹,具有以下代码:

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



第三:在我们的'settings.py'中添加中间件



我们需要在settings.py中查找 MIDDLEWARE_CLASSES ,我们需要添加我们的中间件(添加它位于最后的位置)。它应该是:

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

We need to look for the MIDDLEWARE_CLASSES 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 !

这篇关于如何在django中设置自定义中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆