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

查看:24
本文介绍了如何在 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、urls、templates...放在同一个文件夹

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

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

现在我们应该为我们的自定义中间件创建一个文件,在这个例子中,假设我们想要一个根据用户的 IP 过滤用户的中间件,我们在 filter_ip_middleware.py 中创建一个名为 filter_ip_middleware.py 的文件带有此代码的 strong>middleware 文件夹:

Now we should create a file for our custom middleware, in this example let's suppose 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'中添加中间件

我们需要寻找:

  • MIDDLEWARE_CLASSES (django <1.10)
  • 中间件 (django >= 1.10)

在 settings.py 中,我们需要添加我们的中间件(在最后位置添加).它应该看起来像:

Inside the settings.py we need to add our middleware (Add it in the last position). It should look 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天全站免登陆