我有一个来自Django REST Framework的TokenAuthentication的令牌字符串。我需要得到相应的用户对象。我该怎么做呢?
uklbhaso1#
from rest_framework.authtoken.models import Token user = Token.objects.get(key='token string').user
字符串
i1icjdpr2#
如果你直接从Token类调用user对象,如@aliva的解决方案所示,你将得到一个原始的部分Django User,只有数据库中的字段。如果你需要得到真实的user对象,例如它的计算属性,你可以这样做:
Token
from rest_framework.authtoken.models import Token user_id = Token.objects.get(key=request.auth.key).user_id user = User.objects.get(id=user_id)
aor9mmx13#
下面是**The default authorization token model**:
The default authorization token model
@python_2_unicode_compatible class Token(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField(_("Created"), auto_now_add=True) class Meta: # Work around for a bug in Django: # https://code.djangoproject.com/ticket/19422 # # Also see corresponding ticket: # https://github.com/encode/django-rest-framework/issues/705 abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(Token, self).save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key
字符串正如你所看到的,这个模型与User模型有OneOnOne关系。所以如果你想得到User,而不是Map到特定的Token:
User
from rest_framework.authtoken.models import Token try: Token.objects.get(key="token").user except Token.DoesNotExist: pass
型
更多信息请参见Authentication documents
yhived7q4#
一个更好的方法是简单地调用request.user,因为对Token的访问意味着一个经过身份验证的请求。DjangoRestFramework在成功的TokenAuthentication上提供对request.auth和request.user的访问。
request.user
request.auth
wfveoks05#
假设在Django Rest Framework中获取auth token时,需要获取userid和username更多信息可从https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint获取
# in views.py from rest_framework.auth.models import Token from rest_framework.auth.views import ObtainToken from rest_framework.response import Response class MyObtainToken(ObtainToken): """Return User Info along with token""" def post(self, request, *arg, **kwarg) serializer = self.serializer_class(request.data, context={'request':request}) serializer.is_valid(raise_exception=True) user = serializer.valided_data['user'] token, _ = Token.objects.get_or_create(user) return Response( { 'token': token.key, 'username': user.username, 'userid': user.pk }) # in urls.py urlpatterns += [path(r'api/obtain_auth_token', MyObtainToken.as_view()]
zi8p0yeb6#
为了简洁起见,您可以使用现有ModelViewSet的@action:
@action
class UserViewSet(viewsets.ModelViewSet): ... @action( detail=False, methods=["get"], url_path=r"current", ) def current_user(self, request): return Response( UserSerializer(request.user, context={"request": request}).data )
字符串然后GET它在:http://localhost:8000/yourapi/users/current/
GET
6条答案
按热度按时间uklbhaso1#
字符串
i1icjdpr2#
如果你直接从
Token
类调用user对象,如@aliva的解决方案所示,你将得到一个原始的部分Django User,只有数据库中的字段。如果你需要得到真实的user对象,例如它的计算属性,你可以这样做:字符串
aor9mmx13#
下面是**
The default authorization token model
**:字符串
正如你所看到的,这个模型与
User
模型有OneOnOne关系。所以如果你想得到
User
,而不是Map到特定的Token
:型
更多信息请参见Authentication documents
yhived7q4#
一个更好的方法是简单地调用
request.user
,因为对Token的访问意味着一个经过身份验证的请求。DjangoRestFramework在成功的TokenAuthentication上提供对request.auth
和request.user
的访问。wfveoks05#
假设在Django Rest Framework中获取auth token时,需要获取userid和username
更多信息可从https://www.django-rest-framework.org/api-guide/authentication/#by-exposing-an-api-endpoint获取
字符串
zi8p0yeb6#
为了简洁起见,您可以使用现有ModelViewSet的
@action
:字符串
然后
GET
它在:http://localhost:8000/yourapi/users/current/