如何在Django中设置自定义中间件 [英] How to set up custom middleware in Django

查看:198
本文介绍了如何在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 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  

但是我应该把这节课放在哪里?我是否要创建一个中间件应用并将其放在其中,然后在 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 settings.middleware?

推荐答案

第一:路径结构



如果没有,则需要创建中间件

yourproject/yourapp/middleware

文件夹中间件应与settings.py,url,模板...

重要提示:不要忘记在中间件文件夹中创建__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中添加中间件



我们需要寻找:

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

We need to look for:


  • MIDDLEWARE_CLASSES (django< 1.10)

  • MIDDLEWARE (django> = 1.10)

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

在settings.py内部,我们需要添加中间件(将其添加到最后一个位置)。

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天全站免登陆