python - add cookie to cookiejar

后端 未结 2 1813
梦毁少年i
梦毁少年i 2021-02-08 00:49

How do I create a cookie and add it to a CookieJar instance in python? I have all the info for the cookie (name, value, domain, path, etc) and I don\'t want to extract a new co

2条回答
  •  醉话见心
    2021-02-08 01:51

    The crucial point here is that method cj.set_cookie expects an object of class cookielib.Cookie as its parameter (so yes, there is another Cookie class), not an object of class Cookie.SimpleCookie (or any other class found in module Cookie). These classes are (as observed) simply not compatible, despite the confusing similarity of names.

    Note that the parameter list of the constructor for cookielib.Cookie might have changed at some point in the past (and might change again in the future as this class does not seem to be expected to be used outside of cookielib), at least help(cookielib.Cookie) currently gives me

    # Cookie(version, name, value, port, port_specified, domain,
    # domain_specified, domain_initial_dot, path, path_specified,
    # secure, expires, discard, comment, comment_url, rest, rfc2109=False)
    

    Note the additional expires parameter and the parameter rfc2109 used but not documented in the code in @Michael's answer above, so the example should become something like

    c = Cookie(None, 'asdf', None, '80', True, 'www.foo.bar', 
       True, False, '/', True, False, '1370002304', False, 'TestCookie', None, None, False)
    

    (also replacing some Boolean constants for None where applicable).

提交回复
热议问题