[英]Rewriting DRF token auth
我希望允許用戶擁有多個令牌,因此決定重寫令牌模型。 結果創建
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'.
任何提示可能是什么?
Token類修改是這樣的:
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
我設法找到了問題所在。 在同一個文件中使用 TokenAuth 擴展會導致一些導入錯誤,似乎試圖在其他文件中導入自己。 解決方案正在移動
class TokenAuthentication(rest_framework.authentication.TokenAuthentication):
model = Token
到另一個文件
請確保你已經導入TokenAuthentication
從rest_framework.authentication
,而不是從rest_framework.authToken
我一直在處理這個錯誤。 事實證明,這與其他人所說的令牌有關。 這不完全是“修復”,但它為我消除了錯誤:
我正在使用 simplejwt 並注釋掉導入: from rest_framework_simplejwt.tokens import RefreshToken
並且還使用導入注釋掉了函數。
在這之后我的錯誤得到了解決。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.