20.22. Cookie — HTTP state management¶
Note
The Cookie module has been renamed to http.cookies in Python
3.0. The 2to3 tool will automatically adapt imports when converting
your sources to 3.0.
The Cookie module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only
cookies, and provides an abstraction for having any serializable data-type as
cookie value.
The module formerly strictly applied the parsing rules described in the RFC 2109 and RFC 2068 specifications. It has since been discovered that MSIE 3.0x doesn’t follow the character rules outlined in those specs. As a result, the parsing rules used are a bit less strict.
Note
On encountering an invalid cookie, CookieError is raised, so if your
cookie data comes from a browser you should always prepare for invalid data
and catch CookieError on parsing.
-
exception
Cookie.CookieError¶ Exception failing because of RFC 2109 invalidity: incorrect attributes, incorrect Set-Cookie header, etc.
-
class
Cookie.BaseCookie([input])¶ This class is a dictionary-like object whose keys are strings and whose values are
Morselinstances. Note that upon setting a key to a value, the value is first converted to aMorselcontaining the key and the value.If input is given, it is passed to the
load()method.
-
class
Cookie.SimpleCookie([input])¶ This class derives from
BaseCookieand overridesvalue_decode()andvalue_encode()to be the identity andstr()respectively.
-
class
Cookie.SerialCookie([input])¶ This class derives from
BaseCookieand overridesvalue_decode()andvalue_encode()to be thepickle.loads()andpickle.dumps().Deprecated since version 2.3:
Deprecated since version 2.3: Reading pickled values from untrusted cookie data is a huge security hole, as pickle strings can be crafted to cause arbitrary code to execute on your server. It is supported for backwards compatibility only, and may eventually go away.
-
class
Cookie.SmartCookie([input])¶ This class derives from
BaseCookie. It overridesvalue_decode()to bepickle.loads()if it is a valid pickle, and otherwise the value itself. It overridesvalue_encode()to bepickle.dumps()unless it is a string, in which case it returns the value itself.Deprecated since version 2.3:
Deprecated since version 2.3: The same security warning from
SerialCookieapplies here.