如何在set_cookie函数django中添加samesite = None?

时间:2020-10-13 06:16:19

标签: python django cookies django-views middleware

我想在samesite中将None属性添加为set_cookie function

这是我称为set_cookie function

的代码
redirect = HttpResponseRedirect( '/m/' )
redirect.set_cookie( 'access_token', access_token, max_age=60 * 60 )

这是我设置Cookie的功能

def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
               domain=None, secure=False, httponly=False):
    self.cookies[key] = value
    if expires is not None:
        if isinstance(expires, datetime.datetime):
            if timezone.is_aware(expires):
                expires = timezone.make_naive(expires, timezone.utc)
            delta = expires - expires.utcnow()
            delta = delta + datetime.timedelta(seconds=1)
            expires = None
            max_age = max(0, delta.days * 86400 + delta.seconds)
        else:
            self.cookies[key]['expires'] = expires
    else:
        self.cookies[key]['expires'] = ''
    if max_age is not None:
        self.cookies[key]['max-age'] = max_age
        # IE requires expires, so set it if hasn't been already.
        if not expires:
            self.cookies[key]['expires'] = cookie_date(time.time() +
                                                       max_age)
    if path is not None:
        self.cookies[key]['path'] = path
    if domain is not None:
        self.cookies[key]['domain'] = domain
    if secure:
        self.cookies[key]['secure'] = True
    if httponly:
        self.cookies[key]['httponly'] = True

2 个答案:

答案 0 :(得分:1)

如果您使用的是django2.x或更旧的版本,则可以使用此库来更改标志:https://pypi.org/project/django-cookies-samesite/

如果您使用的是django3.x,它应该是内置的

答案 1 :(得分:0)

您可以只对 HTTP 响应使用 set_cookie('name', 'value')

喜欢return HttpResponse("hi").set_cookie('name', 'Aniket')