使用@decorator_from_middleware时无法导入自定义中间件. (非全球中间件) [英] Can't import custom Middleware whilst using @decorator_from_middleware. (Non Global Middleware)

查看:127
本文介绍了使用@decorator_from_middleware时无法导入自定义中间件. (非全球中间件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些自定义中间件来检查用户的身份验证.这很好用,但是我不想在每个URL上都运行该中间件.

I was using some custom middleware to check auth of users. This was working great but I don't want to run this middleware on every url.

建议指向使用@decorator_from_middleware 在要运行中间件的每个视图之前,这是理想的.我的某些观点应该是全球性的,而另一些观点应该在auth之后.

Suggestions point towards using @decorator_from_middleware before each view that you want middleware to run, this would be ideal. Some of my view should be global, others behind auth.

我似乎无法导入中间件以在视图文件中对其进行调用.

I cant seem to import the middleware to call it in the views file.

我的views.py:

My views.py:

from myapp.middleware import *

@decorator_from_middleware(AuthCheckMiddleware)
def index(request):
    return render(request, "index.html")

我的myapp.middleware.authCheck.py:

My myapp.middleware.authCheck.py:

class AuthCheckMiddleware(object):
def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request):
    #CHECK AUTH HERE
    response = self.get_response(request)
    return response

def process_exception(self, request, exception): 
    return None

我得到的错误:

  File "/vagrant/myapp/django-project/isadmin/web/views.py", line 93, in <module>
@decorator_from_middleware(AuthCheckMiddleware)
NameError: name 'AuthCheckMiddleware' is not defined

推荐答案

这是标准的Python行为.除非您在myapp.middleware的__init__.py中明确导入AuthCheckMiddleware,否则它不会被from myapp.middleware import *导入.

This is standard Python behaviour. Unless you explicitly import AuthCheckMiddleware in the __init__.py of myapp.middleware, it won't be imported by from myapp.middleware import *.

但是实际上您绝对不应该这样做. import *很少有很好的理由.始终明确导入您需要的东西.

But really you should never be doing this anyway. There's very rarely a good reason to do import *; always import the things you need explicitly.

from myapp.middleware.authCheck import AuthCheckMiddleware

还请注意,Python样式用于模块具有lower_case_with_underscore名称:应该为auth_check.py.

Also note, Python style is for modules to have lower_case_with_underscore names: it should be auth_check.py.

还请注意,Python不需要或不需要每个类都在单独的文件中,因此您可能拥有包含多个类(包括AuthCheckMiddleware)的myapp/middleware.py.这样,您的原始代码就可以了(尽管使用import *仍然不是一个好主意).

Also also note, Python does not require or expect each class to be in a separate file, so you could have myapp/middleware.py containing several classes including AuthCheckMiddleware. Then your original code would have worked (although it's still not a good idea to use import *).

这篇关于使用@decorator_from_middleware时无法导入自定义中间件. (非全球中间件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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