我想允许用户拥有多个令牌,因此决定重写令牌模型。结果创建了
class TokenAuthentication(rest_framework.authentication.TokenAuthentication):
model = Token
在我的设置中添加到REST_FRAMEWORK
'DEFAULT_AUTHENTICATION_CLASSES': (
'users.authentication.TokenAuthentication',
)
还修改了
class ObtainAuthToken(APIView):
authentication_classes = ()
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
name = serializer.validated_data['name']
token, created = Token.objects.get_or_create(user=user, name=name)
return Response({'token': token.key})
obtain_auth_token = ObtainAuthToken.as_view()
和AuthTokenSerializer返回名称
最终在网址中得到了
url(r'^token-auth/', obtain_auth_token),
我认为一切都是正确的,但不断收到错误
File "/home/me/code/python/OCManager/core/users/authentication.py", line 4, in <module>
from rest_framework.views import APIView
ImportError: cannot import name 'APIView'
和
ImportError: Could not import 'users.authentication.TokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'APIView'.
任何暗示它可能是什么?
令牌类修改是这样的:
class Token(rest_framework.authtoken.models.Token):
# key is no longer primary key, but still indexed and unique
key = models.CharField(_("Key"), max_length=40, db_index=True, unique=True)
# relation to user is a ForeignKey, so each user can have more than one token
user = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='auth_tokens',
on_delete=models.CASCADE, verbose_name=_("User")
)
name = models.CharField(_("Name"), max_length=64)
class Meta:
unique_together = (('user', 'name'),)
def __str__(self):
return self.user.username + " - " + self.name
答案 0 :(得分:0)
我设法找到了什么问题。将TokenAuth扩展名放在同一个文件中导致一些导入错误,似乎试图在其他文件中导入自己。解决方案正在移动
void Complex::sum(Complex r, Complex i)
{
sum = r + i; //error here under "sum" and "+"
}
到另一个档案
答案 1 :(得分:0)
请确保您是从TokenAuthentication
而不是从rest_framework.authentication
导入rest_framework.authToken
答案 2 :(得分:0)
我一直在处理这个错误。事实证明,这与其他人所说的令牌有关。这不完全是“修复”,但它为我消除了错误:
我使用的是 simplejwt 并注释掉了导入:
from rest_framework_simplejwt.tokens import RefreshToken
并且还用import注释掉了这个函数。
我的错误在此之后得到解决。