如何在 Django 视图中添加对 cookie 的访问

How add access to cookie in Django views

你好朋友,我是初学者,我在下面添加了一个代码。

我有使用 refresh_token 的视图。 我的老板告诉我添加对 cookie 的访问权限,但我不知道如何添加它?在哪里添加? 任何人都可以给我一个解决方案或给我发一份 link 吗? 如果对 cookie 和完整的请求结构知之甚少,能否给我一个 link 来描述我很感激。

from django.utils.translation import gettext as _
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from src.apps.accounts.services import refresh
from src.errors import BadRequestException, ErrorEnum
from settings import ACCESS_TTL
from django.core.cache import cache

class 刷新令牌(APIView): permission_classes = []

def post(self, *args, **kwargs):
    refresh_token = self.request.data.get("refresh_token")
    if refresh_token is None:
        raise BadRequestException(
            message={
                "refresh_token": _("refresh_token must be submitted.")
            },
            error_type=[ErrorEnum.RefreshToken.REFRESH_IS_EMPTY],
        )
    access_token, refresh_token = refresh(token=refresh_token)

    response= Response(
        data={
            "ok": True,
            "data": {
                "access_token": access_token,
                "refresh_token": refresh_token,
            },
            "status": status.HTTP_200_OK,
        },
        status=status.HTTP_200_OK,
        headers={"HTTP_ACCESS":access_token},
    )
    return response

您可以像这样在 cookie 中设置令牌:

def your_view(request):
    response = HttpResponse()
    response.set_cookie('access_token', your_access_token, httpOnly=True)
    response.set_cookie('refresh_token', your_refresh_token, httpOnly=True)
    return response

你可以用request.COOKIES['access_token']

得到它

您还可以在 header 中 return cookie,如下所示:

headers = {
  'Set-Cookie': 'access_token='+ access_token+';'
}