错误日志
ImportError: Could not import 'myapp.api.base.MyAuth' for API setting
'DEFAULT_AUTHENTICATION_CLASSES'. AttributeError: module 'myapp.api.base' has no
attribute 'MyAuth'.
我采用Django构建一个项目:
setting.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES":['myapp.api.base.MyAuth']
}
from rest_framework import exceptions
#注释掉APIView
#from rest_framework.views import APIView
from com.base.util import LogUtil
# 基础认证
class MyAuth(object):
def authenticate(self, request):
print('我的认证')
token = request.GET.get('token')
if not token:
raise exceptions.AuthenticationFailed('用户认证失败')
return ('alex', None)
def authenticate_header(self, request):
pass
#移动到这
from rest_framework.views import APIView
# 基类
class BaseView(APIView):
# authentication_classes = [MyAuth, ]
def dispatch(self, request, *args, **kwargs):
print('base-dispatch')
func = super(BaseView, self).dispatch(request, *args, **kwargs)
return func
之前一直没问题,我就是将import往上移动了,导致错误出现。
实际上,只需要把“from rest_framework.views import APIView”移动到BaseView上方,MyAuth下发就能解决问题。
没太习惯Python的编写方式,才导致这个问题,很尴尬,记录下.
总结:
Python中同一个文件中写多个类的时候,最好把属于当前类的引用“import”写到自己类上方,最好一个文件写一个类。
本文解决了一个Django项目中关于自定义认证类导致的ImportError及AttributeError问题。通过调整import语句的位置,解决了错误。
742





