我怎么知道请求.用户从Django的角度看?

2024-05-20 20:46:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎么知道请求.用户从哪里来?在

我有一个testrequestuserapi视图:

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时。 我可以得到请求user(谁请求这个API)。在

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

是通过饼干吗?或者一些标记(在我的测试项目中,我登录了。但是我在访问API时没有把令牌放到请求中,仍然在后台获取用户需求用户)? 在


编辑-1

我的项目中有django build-in认证和{}:

下面的认证在我安装的应用程序中:

^{pr2}$

我还想知道前端通过什么来标识后端的用户,它使用cookie吗?还是象征?我使用rest auth在登录时生成一个令牌。在


Tags: the用户selfapigetreturnrequestdef
1条回答
网友
1楼 · 发布于 2024-05-20 20:46:40

我假设你使用的是Django's built-in authentication system-也就是说,你的设置中安装了django.contrib.auth。在

中间件有机会在您的任何视图收到之前拦截request。 此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)

相关问题 更多 >