【问题标题】:Conditional Django Middleware (or how to exclude the Admin System)条件 Django 中间件(或如何排除管理系统)
【发布时间】:2010-11-04 21:48:25
【问题描述】:

我想使用我在整个网站上编写的一些中间件(大量页面,因此我选择不使用装饰器,因为我想将代码用于所有页面)。唯一的问题是我不想将中间件用于管理代码,而且它似乎对它们有效。

有什么方法可以配置 settings.py 或 urls.py,或者代码中的某些内容以防止它在管理系统的页面上执行?

非常感谢任何帮助,

干杯

保罗

【问题讨论】:

    标签: python django django-admin django-middleware


    【解决方案1】:

    你不需要到处乱走。

    如果您想从视图中排除单个中间件,您必须首先导入该中间件并执行以下操作:

    from django.utils.decorators import decorator_from_middleware
    
    from your.path.middlewares import MiddleWareYouWantToExclude
    
    @decorator_from_middleware(MiddleWareYouWantToExclude)
    def your_view(request):
        ....
    

    如果您想排除 ALL 中间件,无论它们是/做什么,请执行以下操作:

    from django.conf import settings
    from django.utils.module_loading import import_string
    from django.utils.decorators import decorator_from_middleware
    
    def your_view(request):
        ...
    
    # loop over ALL the active middleware used by the app, import them
    # and add them to the `decorator_from_middleware` decorator recursively
    for m in [import_string(s) for s in settings.MIDDLEWARE]:
        your_view = decorator_from_middleware(m)(your_view)
    

    【讨论】:

      【解决方案2】:

      一般方法是(基于 piquadrat 的回答)

      def process_request(self, request):
          if request.path.startswith(reverse('admin:index')):
              return None
          # rest of method
      

      这样,如果有人将/admin/ 更改为/django_admin/,您仍然可以得到保障。

      【讨论】:

      • 请记住,您的路径可能有语言前缀! (例如/en/admin)
      【解决方案3】:

      我想这样做的主要原因是在中间件中使用了 XML 解析器,这会弄乱非 XML 下载。我已经添加了一些额外的代码来检测代码是否是 XML,而不是尝试解析它不应该解析的任何内容。

      对于其他不方便的中间件,我可能会使用上面提到的 piquadrat 方法,或者只是使用视图装饰器 - Cheers piquadrat!

      【讨论】:

        【解决方案4】:

        您可以检查 process_request 中的路径(以及中间件中的任何其他 process_*-methods)

        def process_request(self, request):
            if request.path.startswith('/admin/'):
                return None
            # rest of method
        
        def process_response(self, request, response):
            if request.path.startswith('/admin/'):
                return response
            # rest of method
        

        【讨论】:

          猜你喜欢
          • 2017-07-26
          • 2017-01-06
          • 1970-01-01
          • 2015-03-21
          • 2021-12-14
          • 2011-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多