gpt4 book ai didi

python - 我如何知道 request.user 来自 Django View 中的位置?

转载 作者:太空宇宙 更新时间:2023-11-03 14:27:16 24 4
gpt4 key购买 nike

我如何知道request.user来自哪里?

我有一个 TestRequestUserAPIView:

class TestRequestUserAPIView(View):

def dispatch(self, request, *args, **kwargs):
result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs)
return result

def get(self, request):
user = request.user # this line I get the user (who access the API)
return HttpResponse("ok")

当执行此行时user = request.user。我可以获得请求用户(请求此API的人)。

我想知道用户是如何在请求中生成的,为什么我在像Chrome这样的浏览器中请求这个API,我的请求将具有用户属性?

是通过cookie吗?或者一些 token (在我的测试项目中,我登录了。但是我在访问API时没有将 token 放入请求中,仍然在后端reqest.user中获取用户)?

<小时/>

编辑-1

我的项目中有 django build-in auth 和 rest-auth:

以下身份验证位于我的 INSTALLED_APPS 中:

'django.contrib.auth',
'rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',

我还想知道前端通过什么向后端传递用户身份,它是否使用cookie?或 token ?我在登录时使用rest-auth 生成 token 。

最佳答案

我假设您正在使用 Django's built-in authentication system - 即您的设置安装的应用程序中包含 django.contrib.auth

中间件有机会在您的任何 View 收到请求之前拦截该请求。这个 request.user 属性由 Django 的 auth 中间件 here 设置。 :

class RemoteUserMiddleware(MiddlewareMixin):
"""
Middleware for utilizing Web-server-provided authentication.
If request.user is not authenticated, then this middleware attempts to
authenticate the username passed in the ``REMOTE_USER`` request header.
If authentication is successful, the user is automatically logged in to
persist the user in the session.
The header used is configurable and defaults to ``REMOTE_USER``. Subclass
this class and change the ``header`` attribute if you need to use a
different header.
"""
...
def process_request(self, request):
...
# We are seeing this user for the first time in this session, attempt
# to authenticate the user.
user = auth.authenticate(request, remote_user=username)
if user:
# User is valid. Set request.user and persist user in the session
# by logging the user in.
request.user = user
auth.login(request, user)

关于python - 我如何知道 request.user 来自 Django View 中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com