Home > Mobile >  How do I make custom cookie attributes in http.cookiejar?
How do I make custom cookie attributes in http.cookiejar?

Time:10-03

I am trying to add a cookie to my python http request that looks something like the following:

 {
    "domain": ".foo.com",
    "hostOnly": false,
    "httpOnly": false,
    "name": "name",
    "path": "/",
    "sameSite": null,
    "secure": false,
    "session": true,
    "storeId": null,
    "value": "none"
  }

When I do something like,

jar = cookielib.CookieJar()
cookies = json.loads(open('cookies.json', 'r').read())
for i in cookies:

        print(i['expirationDate'])
        jar.set_cookie(i['name'], expirationDate = i['expirationDate'], hostOnly=i["hostOnly"], httpOnly = i["httpOnly"], sameSite = i["sameSite"], secure = i["secure"], session = i["session"], storeId = i["storeId"], value = i["value"])

It throws the following error:

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/bin/Users/{me}/PycharmProjects/{project name}/{file name}.py", line {line}, in <module>
    jar.set_cookie(i['name'], hostOnly=i["hostOnly"], httpOnly = i["httpOnly"], sameSite = i["sameSite"], secure = i["secure"], session = i["session"], storeId = i["storeId"], value = i["value"])
TypeError: set_cookie() got an unexpected keyword argument 'hostOnly'

I was wondering how I could add a cookie with special attributes

Thank you in advanced

CodePudding user response:

Make a class for a cookie like the one below

import time
class cookie:
    def __init__(self, name, version, path, domain, expirationDate, hostOnly, httpOnly, sameSite, secure, session, storeId, value):
        self.name = name
        self.version = version
        self.path = path
        self.domain = domain
        self.expirationDate = expirationDate
        self.hostOnly = hostOnly
        self.httpOnly = httpOnly
        self.sameSite = sameSite
        self.secure = secure
        self.session = session
        self.storeId = storeId
        self.value = value

    def is_expired(self, now):
        if now > time.time():
            return True
        return False

You can then pass any valid cookie object into jar.set_cookie()

  • Related