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