Python 如何知道request.user在Django视图中的位置?
我如何知道request.user来自何处 我有一个TestRequestUserAPIView:Python 如何知道request.user在Django视图中的位置?,python,django,Python,Django,我如何知道request.user来自何处 我有一个TestRequestUserAPIView: class TestRequestUserAPIView(View): def dispatch(self, request, *args, **kwargs): result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs) return result
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,我请求将具有用户属性
是不是通过饼干?或者一些令牌(在我的测试项目中,我登录了。但是我在访问API时没有将令牌放入请求中,仍然在backend request.user中获取用户)
编辑-1 我的项目中有django
内置
auth和rest auth
:
下面的认证在我安装的应用程序中:
'django.contrib.auth',
'rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',
我还想知道前端传递什么给后端的用户身份,它是否使用cookie?还是代币?我使用rest auth在登录时生成一个令牌 我假设您正在使用-也就是说,您安装的应用程序的设置中包含了django.contrib.auth
在任何视图收到请求之前,中间件都有机会拦截该请求。
此request.user
属性由Django的auth中间件设置:
谢谢你的回答,我可以在我的项目中调试你的post代码吗?是的,你可以,在你的本地安装中找到
django/contrib/auth/middleware.py
文件,并在其中设置一个断点。老实说,我还想知道前端为用户身份向后端传递什么,它使用cookie吗?还是代币?我在登录时使用rest auth生成一个令牌。它同时使用这两个令牌(cookie中的会话令牌)。
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)