作者:黄力2502860237_367 | 来源:互联网 | 2023-02-01 17:46
我在Django中使用默认视图生成标记:
url(r'^login/', rest_auth_views.obtain_auth_token),
我有一个问题,因为我的前端不知道当前登录的用户ID是什么.
我应该使用令牌返回它还是创建另一个请求?
我知道有很多不同的方法,但我想选择最优的解决方案.
1> zaidfazil..:
您可以覆盖rest_framework.authtoken.views.ObtainAuthToken.post
以获得所需的结果.
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.
希望有所帮助.