django - 为什么“本机”视图和 ModelViewSet 之间的请求对象不一样?
问题描述
我正在使用 Django Rest Framework (DRF) 构建 API,并通过社交应用启用身份验证/注册。
为了通过他们的社交账户对用户进行身份验证,我使用了 Django rest-framework Social Oauth2,它就像一个魅力。为了确保我的用户已登录,我在应用程序的 views.py 中创建了一个非常简单的视图:
def index(request):
return HttpResponse("is_anonymous: %s" % request.user.is_anonymous)
浏览器中的结果如下(表示用户已登录):
is_anonymous: 假
现在,当我使用 DRF 构建 API 时,我可能需要在我的一个视图集中检索当前用户的一些数据(来自 request.user),但在以下代码中,结果不是我所期望的:
class HelloViewSet(viewsets.ModelViewSet):
queryset = Hello.objects.all()
serializer_class = HelloSerializer
# This is just a random ViewSet, what is
# important is the custom view below
@action(detail=False)
def test(self, request):
return Response(request.user.is_anonymous)
这里的结果显示用户没有登录:
真的
所以第一个视图显示 request.user.is_anonymous = False,第二个视图显示 request.user.is_anonymous = True。两个视图都在同一个应用程序的同一个文件views.py 中。
我在这里想念什么?我们不应该在 API REST 中获取用户实例吗?
解决方案
As neverwalkaloner mentioned in the in the comments, the problem was that I didn't pass any access_token in the header via Authorization: Bearer <token>
, so of course the server wasn't able to identify the "logged" user that was making the request. Using curl (or Postman) I could add this token for checking purpose and it worked.
推荐阅读
- c# - 视图没有被模型更新
- docker - 使用 Dockerfile 将文件从容器复制到主机
- angularjs - 从指令调用 $http 在 angularjs watch 中
- r - addMarkers 需要 R Shiny 中的非 NULL 经度/纬度值
- forms - Typ3 v8 表单检查值到打字稿和 yaml
- c# - 如何每 5 秒刷新一次图像?
- javascript - 计算字符串过去某个字符(JS)中的字符
- geode - 无法从 Geode 中的客户端动态创建区域
- java - Spring Boot 中的 Java-SOAP 请求正文元素顺序问题
- php - 执行 PHPUnit 0 测试的 Phing