python - 如何在 Django 中返回带有 token 的用户 ID?

标签 python django python-2.7 authorization token

我使用 Django 中的默认 View 生成 token :

url(r'^login/', rest_auth_views.obtain_auth_token),

我有一个问题,因为我的前端不知道当前登录的用户 ID 是什么。

我应该用 token 返回它还是创建其他请求?

我知道有很多不同的方法,但我想选择最优的解决方案。

最佳答案

您可以覆盖 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 View 类的post方法。在这里,我所做的就是调用父类来获取 token ,然后查找该 token 以找到关联的用户 ID。

希望对您有所帮助。

关于python - 如何在 Django 中返回带有 token 的用户 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44448878/

相关文章:

python - 在 Python/django 中读取 json 时可能出现多少异常?

python - Django:规范化用户提交的模型数据以在模板中显示

python - 使用 BeautifulSoup 提取链接的标题

python-2.7 - Python Pandas 将列中的子字符串替换为另一列中的子字符串

python - 通过python中的Elastic Search搜索唯一值

python - 自动将绘图保存在 ipython 笔记本中

python - scipy.stats.poisson 中的 mu、loc 和 size 是什么意思?

django:form.fields 不遍历实例字段

django - 在 Django 1.11 中为自定义用户添加额外的字段

python - 读取 .txt 文件中的数据(不包括页眉和页脚)