1

How do I add the SameSite parameter to a cookie in Python 2.7?

I have seen this How do I set the `SameSite` attribute of HTTP cookies in python?, but it's not clear to me if this works for Python 2.7 or how I'd even combine it with the code I have:

response.set_cookie(key="", value="", max_age="", expires="", path="/",domain="",secure=None,httponly=True)
return response

I use Django so I create the response like so:

response = render(request, "template.html", {})
user984003
  • 28,050
  • 64
  • 189
  • 285

1 Answers1

1

I figured it out. I use (an old version of) Django with Python 2.7 and add the cookie to the response object like this:

response["Set-Cookie"] = COOKIE_NAME+'='+COOKIE_VALUE+';expires='+EXPIRES+';Secure;SameSite=None;HttpOnly;Path=/;domain='+MY_DOMAIN+';'

Note that you can only set it once like this since the value gets overwritten. Presumably you can set more than one cookie, but haven't needed it. You can still set cookies using response.set_cookie(), at least before you do this.

Expires, I get like this:

max_age = 315360000
expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
user984003
  • 28,050
  • 64
  • 189
  • 285