| 1 |
:mod:`Cookie` --- HTTP state management |
| 2 |
======================================= |
| 3 |
|
| 4 |
.. module:: Cookie |
| 5 |
:synopsis: Support for HTTP state management (cookies). |
| 6 |
.. moduleauthor:: Timothy O'Malley <[email protected]> |
| 7 |
.. sectionauthor:: Moshe Zadka <[email protected]> |
| 8 |
|
| 9 |
.. note:: |
| 10 |
The :mod:`Cookie` module has been renamed to :mod:`http.cookies` in Python |
| 11 |
3. The :term:`2to3` tool will automatically adapt imports when converting |
| 12 |
your sources to Python 3. |
| 13 |
|
| 14 |
**Source code:** :source:`Lib/Cookie.py` |
| 15 |
|
| 16 |
-------------- |
| 17 |
|
| 18 |
The :mod:`Cookie` module defines classes for abstracting the concept of |
| 19 |
cookies, an HTTP state management mechanism. It supports both simple string-only |
| 20 |
cookies, and provides an abstraction for having any serializable data-type as |
| 21 |
cookie value. |
| 22 |
|
| 23 |
The module formerly strictly applied the parsing rules described in the |
| 24 |
:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that |
| 25 |
MSIE 3.0x doesn't follow the character rules outlined in those specs and also |
| 26 |
many current day browsers and servers have relaxed parsing rules when comes to |
| 27 |
Cookie handling. As a result, the parsing rules used are a bit less strict. |
| 28 |
|
| 29 |
The character set, :data:`string.ascii_letters`, :data:`string.digits` and |
| 30 |
``!#$%&'*+-.^_`|~`` denote the set of valid characters allowed by this module |
| 31 |
in Cookie name (as :attr:`~Morsel.key`). |
| 32 |
|
| 33 |
|
| 34 |
.. note:: |
| 35 |
|
| 36 |
On encountering an invalid cookie, :exc:`CookieError` is raised, so if your |
| 37 |
cookie data comes from a browser you should always prepare for invalid data |
| 38 |
and catch :exc:`CookieError` on parsing. |
| 39 |
|
| 40 |
|
| 41 |
.. exception:: CookieError |
| 42 |
|
| 43 |
Exception failing because of :rfc:`2109` invalidity: incorrect attributes, |
| 44 |
incorrect :mailheader:`Set-Cookie` header, etc. |
| 45 |
|
| 46 |
|
| 47 |
.. class:: BaseCookie([input]) |
| 48 |
|
| 49 |
This class is a dictionary-like object whose keys are strings and whose values |
| 50 |
are :class:`Morsel` instances. Note that upon setting a key to a value, the |
| 51 |
value is first converted to a :class:`Morsel` containing the key and the value. |
| 52 |
|
| 53 |
If *input* is given, it is passed to the :meth:`load` method. |
| 54 |
|
| 55 |
|
| 56 |
.. class:: SimpleCookie([input]) |
| 57 |
|
| 58 |
This class derives from :class:`BaseCookie` and overrides :meth:`value_decode` |
| 59 |
and :meth:`value_encode` to be the identity and :func:`str` respectively. |
| 60 |
|
| 61 |
|
| 62 |
.. class:: SerialCookie([input]) |
| 63 |
|
| 64 |
This class derives from :class:`BaseCookie` and overrides :meth:`value_decode` |
| 65 |
and :meth:`value_encode` to be the :func:`pickle.loads` and |
| 66 |
:func:`pickle.dumps`. |
| 67 |
|
| 68 |
.. deprecated:: 2.3 |
| 69 |
Reading pickled values from untrusted cookie data is a huge security hole, as |
| 70 |
pickle strings can be crafted to cause arbitrary code to execute on your server. |
| 71 |
It is supported for backwards compatibility only, and may eventually go away. |
| 72 |
|
| 73 |
|
| 74 |
.. class:: SmartCookie([input]) |
| 75 |
|
| 76 |
This class derives from :class:`BaseCookie`. It overrides :meth:`value_decode` |
| 77 |
to be :func:`pickle.loads` if it is a valid pickle, and otherwise the value |
| 78 |
itself. It overrides :meth:`value_encode` to be :func:`pickle.dumps` unless it |
| 79 |
is a string, in which case it returns the value itself. |
| 80 |
|
| 81 |
.. deprecated:: 2.3 |
| 82 |
The same security warning from :class:`SerialCookie` applies here. |
| 83 |
|
| 84 |
A further security note is warranted. For backwards compatibility, the |
| 85 |
:mod:`Cookie` module exports a class named :class:`~Cookie.Cookie` which is |
| 86 |
just an alias for :class:`SmartCookie`. This is probably a mistake and will |
| 87 |
likely be removed in a future version. You should not use the |
| 88 |
:class:`~Cookie.Cookie` class in your applications, for the same reason why |
| 89 |
you should not use the :class:`SerialCookie` class. |
| 90 |
|
| 91 |
|
| 92 |
.. seealso:: |
| 93 |
|
| 94 |
Module :mod:`cookielib` |
| 95 |
HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie` |
| 96 |
modules do not depend on each other. |
| 97 |
|
| 98 |
:rfc:`2109` - HTTP State Management Mechanism |
| 99 |
This is the state management specification implemented by this module. |
| 100 |
|
| 101 |
|
| 102 |
.. _cookie-objects: |
| 103 |
|
| 104 |
Cookie Objects |
| 105 |
-------------- |
| 106 |
|
| 107 |
|
| 108 |
.. method:: BaseCookie.value_decode(val) |
| 109 |
|
| 110 |
Return a decoded value from a string representation. Return value can be any |
| 111 |
type. This method does nothing in :class:`BaseCookie` --- it exists so it can be |
| 112 |
overridden. |
| 113 |
|
| 114 |
|
| 115 |
.. method:: BaseCookie.value_encode(val) |
| 116 |
|
| 117 |
Return an encoded value. *val* can be any type, but return value must be a |
| 118 |
string. This method does nothing in :class:`BaseCookie` --- it exists so it can |
| 119 |
be overridden. |
| 120 |
|
| 121 |
In general, it should be the case that :meth:`value_encode` and |
| 122 |
:meth:`value_decode` are inverses on the range of *value_decode*. |
| 123 |
|
| 124 |
|
| 125 |
.. method:: BaseCookie.output([attrs[, header[, sep]]]) |
| 126 |
|
| 127 |
Return a string representation suitable to be sent as HTTP headers. *attrs* and |
| 128 |
*header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used |
| 129 |
to join the headers together, and is by default the combination ``'\r\n'`` |
| 130 |
(CRLF). |
| 131 |
|
| 132 |
.. versionchanged:: 2.5 |
| 133 |
The default separator has been changed from ``'\n'`` to match the cookie |
| 134 |
specification. |
| 135 |
|
| 136 |
|
| 137 |
.. method:: BaseCookie.js_output([attrs]) |
| 138 |
|
| 139 |
Return an embeddable JavaScript snippet, which, if run on a browser which |
| 140 |
supports JavaScript, will act the same as if the HTTP headers was sent. |
| 141 |
|
| 142 |
The meaning for *attrs* is the same as in :meth:`output`. |
| 143 |
|
| 144 |
|
| 145 |
.. method:: BaseCookie.load(rawdata) |
| 146 |
|
| 147 |
If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values |
| 148 |
found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to:: |
| 149 |
|
| 150 |
for k, v in rawdata.items(): |
| 151 |
cookie[k] = v |
| 152 |
|
| 153 |
|
| 154 |
.. _morsel-objects: |
| 155 |
|
| 156 |
Morsel Objects |
| 157 |
-------------- |
| 158 |
|
| 159 |
|
| 160 |
.. class:: Morsel |
| 161 |
|
| 162 |
Abstract a key/value pair, which has some :rfc:`2109` attributes. |
| 163 |
|
| 164 |
Morsels are dictionary-like objects, whose set of keys is constant --- the valid |
| 165 |
:rfc:`2109` attributes, which are |
| 166 |
|
| 167 |
* ``expires`` |
| 168 |
* ``path`` |
| 169 |
* ``comment`` |
| 170 |
* ``domain`` |
| 171 |
* ``max-age`` |
| 172 |
* ``secure`` |
| 173 |
* ``version`` |
| 174 |
* ``httponly`` |
| 175 |
|
| 176 |
The attribute :attr:`httponly` specifies that the cookie is only transferred |
| 177 |
in HTTP requests, and is not accessible through JavaScript. This is intended |
| 178 |
to mitigate some forms of cross-site scripting. |
| 179 |
|
| 180 |
The keys are case-insensitive. |
| 181 |
|
| 182 |
.. versionadded:: 2.6 |
| 183 |
The :attr:`httponly` attribute was added. |
| 184 |
|
| 185 |
|
| 186 |
.. attribute:: Morsel.value |
| 187 |
|
| 188 |
The value of the cookie. |
| 189 |
|
| 190 |
|
| 191 |
.. attribute:: Morsel.coded_value |
| 192 |
|
| 193 |
The encoded value of the cookie --- this is what should be sent. |
| 194 |
|
| 195 |
|
| 196 |
.. attribute:: Morsel.key |
| 197 |
|
| 198 |
The name of the cookie. |
| 199 |
|
| 200 |
|
| 201 |
.. method:: Morsel.set(key, value, coded_value) |
| 202 |
|
| 203 |
Set the *key*, *value* and *coded_value* attributes. |
| 204 |
|
| 205 |
|
| 206 |
.. method:: Morsel.isReservedKey(K) |
| 207 |
|
| 208 |
Whether *K* is a member of the set of keys of a :class:`Morsel`. |
| 209 |
|
| 210 |
|
| 211 |
.. method:: Morsel.output([attrs[, header]]) |
| 212 |
|
| 213 |
Return a string representation of the Morsel, suitable to be sent as an HTTP |
| 214 |
header. By default, all the attributes are included, unless *attrs* is given, in |
| 215 |
which case it should be a list of attributes to use. *header* is by default |
| 216 |
``"Set-Cookie:"``. |
| 217 |
|
| 218 |
|
| 219 |
.. method:: Morsel.js_output([attrs]) |
| 220 |
|
| 221 |
Return an embeddable JavaScript snippet, which, if run on a browser which |
| 222 |
supports JavaScript, will act the same as if the HTTP header was sent. |
| 223 |
|
| 224 |
The meaning for *attrs* is the same as in :meth:`output`. |
| 225 |
|
| 226 |
|
| 227 |
.. method:: Morsel.OutputString([attrs]) |
| 228 |
|
| 229 |
Return a string representing the Morsel, without any surrounding HTTP or |
| 230 |
JavaScript. |
| 231 |
|
| 232 |
The meaning for *attrs* is the same as in :meth:`output`. |
| 233 |
|
| 234 |
|
| 235 |
.. _cookie-example: |
| 236 |
|
| 237 |
Example |
| 238 |
------- |
| 239 |
|
| 240 |
The following example demonstrates how to use the :mod:`Cookie` module. |
| 241 |
|
| 242 |
.. doctest:: |
| 243 |
:options: +NORMALIZE_WHITESPACE |
| 244 |
|
| 245 |
>>> import Cookie |
| 246 |
>>> C = Cookie.SimpleCookie() |
| 247 |
>>> C["fig"] = "newton" |
| 248 |
>>> C["sugar"] = "wafer" |
| 249 |
>>> print C # generate HTTP headers |
| 250 |
Set-Cookie: fig=newton |
| 251 |
Set-Cookie: sugar=wafer |
| 252 |
>>> print C.output() # same thing |
| 253 |
Set-Cookie: fig=newton |
| 254 |
Set-Cookie: sugar=wafer |
| 255 |
>>> C = Cookie.SimpleCookie() |
| 256 |
>>> C["rocky"] = "road" |
| 257 |
>>> C["rocky"]["path"] = "/cookie" |
| 258 |
>>> print C.output(header="Cookie:") |
| 259 |
Cookie: rocky=road; Path=/cookie |
| 260 |
>>> print C.output(attrs=[], header="Cookie:") |
| 261 |
Cookie: rocky=road |
| 262 |
>>> C = Cookie.SimpleCookie() |
| 263 |
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) |
| 264 |
>>> print C |
| 265 |
Set-Cookie: chips=ahoy |
| 266 |
Set-Cookie: vienna=finger |
| 267 |
>>> C = Cookie.SimpleCookie() |
| 268 |
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') |
| 269 |
>>> print C |
| 270 |
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" |
| 271 |
>>> C = Cookie.SimpleCookie() |
| 272 |
>>> C["oreo"] = "doublestuff" |
| 273 |
>>> C["oreo"]["path"] = "/" |
| 274 |
>>> print C |
| 275 |
Set-Cookie: oreo=doublestuff; Path=/ |
| 276 |
>>> C["twix"] = "none for you" |
| 277 |
>>> C["twix"].value |
| 278 |
'none for you' |
| 279 |
>>> C = Cookie.SimpleCookie() |
| 280 |
>>> C["number"] = 7 # equivalent to C["number"] = str(7) |
| 281 |
>>> C["string"] = "seven" |
| 282 |
>>> C["number"].value |
| 283 |
'7' |
| 284 |
>>> C["string"].value |
| 285 |
'seven' |
| 286 |
>>> print C |
| 287 |
Set-Cookie: number=7 |
| 288 |
Set-Cookie: string=seven |
| 289 |
>>> # SerialCookie and SmartCookie are deprecated |
| 290 |
>>> # using it can cause security loopholes in your code. |
| 291 |
>>> C = Cookie.SerialCookie() |
| 292 |
>>> C["number"] = 7 |
| 293 |
>>> C["string"] = "seven" |
| 294 |
>>> C["number"].value |
| 295 |
7 |
| 296 |
>>> C["string"].value |
| 297 |
'seven' |
| 298 |
>>> print C |
| 299 |
Set-Cookie: number="I7\012." |
| 300 |
Set-Cookie: string="S'seven'\012p1\012." |
| 301 |
>>> C = Cookie.SmartCookie() |
| 302 |
>>> C["number"] = 7 |
| 303 |
>>> C["string"] = "seven" |
| 304 |
>>> C["number"].value |
| 305 |
7 |
| 306 |
>>> C["string"].value |
| 307 |
'seven' |
| 308 |
>>> print C |
| 309 |
Set-Cookie: number="I7\012." |
| 310 |
Set-Cookie: string=seven |
| 311 |
|