如何在Django中返回带有令牌的用户ID? [英] How can I return user ID with token in Django?
问题描述
我使用Django中的默认视图生成令牌:
I generate tokens using default view in Django:
url(r'^login/', rest_auth_views.obtain_auth_token),
我有一个问题,因为我的前端不知道当前登录的用户ID是什么.
I have a problem because my front-end doesn't know what is the currently logged in user ID.
我应该用令牌返回它还是创建另一个请求?
Should I return it with token or maybe create some another request?
我知道有很多不同的方法,但是我想选择最佳的解决方案.
I know that there is a lot of different ways, but I would like to choose the most optimal solution.
推荐答案
您可以覆盖rest_framework.authtoken.views.ObtainAuthToken.post
以获得所需的结果.
You could override rest_framework.authtoken.views.ObtainAuthToken.post
in order to get the result you want.
myapp/views.py
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
class CustomObtainAuthToken(ObtainAuthToken):
def post(self, request, *args, **kwargs):
response = super(CustomObtainAuthToken, self).post(request, *args, **kwargs)
token = Token.objects.get(key=response.data['token'])
return Response({'token': token.key, 'id': token.user_id})
myapp/urls.py
from django.conf.urls import url
from .views import CustomObtainAuthToken
urlpatterns = [
url(r'^authenticate/', CustomObtainAuthToken.as_view()),
]
样本结果
$ http :8000/authenticate/ username=someuser password=secretpassword
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Language: en
Content-Type: application/json
Date: Tue, 22 Mar 2017 18:30:10 GMT
Server: WSGIServer/0.2 CPython/3.5.1
Vary: Accept-Language, Cookie
X-Frame-Options: SAMEORIGIN
{
"id": 16,
"token": "82e0bc9980a6b2c9a70969b0f8dc974418dda399"
}
这里的想法是重写ObtainAuthToken视图类的post方法.在这里,我要做的就是调用父类以获取令牌,然后查找该令牌以找到关联的用户ID.
The idea here is to override the post method of the ObtainAuthToken view class. Here all I have done is call the parent class to get the token, then look up that token to find the associated user id.
希望有帮助.
这篇关于如何在Django中返回带有令牌的用户ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!