| 1 | n/a | #### |
|---|
| 2 | n/a | # Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu> |
|---|
| 3 | n/a | # |
|---|
| 4 | n/a | # All Rights Reserved |
|---|
| 5 | n/a | # |
|---|
| 6 | n/a | # Permission to use, copy, modify, and distribute this software |
|---|
| 7 | n/a | # and its documentation for any purpose and without fee is hereby |
|---|
| 8 | n/a | # granted, provided that the above copyright notice appear in all |
|---|
| 9 | n/a | # copies and that both that copyright notice and this permission |
|---|
| 10 | n/a | # notice appear in supporting documentation, and that the name of |
|---|
| 11 | n/a | # Timothy O'Malley not be used in advertising or publicity |
|---|
| 12 | n/a | # pertaining to distribution of the software without specific, written |
|---|
| 13 | n/a | # prior permission. |
|---|
| 14 | n/a | # |
|---|
| 15 | n/a | # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS |
|---|
| 16 | n/a | # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY |
|---|
| 17 | n/a | # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR |
|---|
| 18 | n/a | # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
|---|
| 19 | n/a | # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, |
|---|
| 20 | n/a | # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS |
|---|
| 21 | n/a | # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR |
|---|
| 22 | n/a | # PERFORMANCE OF THIS SOFTWARE. |
|---|
| 23 | n/a | # |
|---|
| 24 | n/a | #### |
|---|
| 25 | n/a | # |
|---|
| 26 | n/a | # Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp |
|---|
| 27 | n/a | # by Timothy O'Malley <timo@alum.mit.edu> |
|---|
| 28 | n/a | # |
|---|
| 29 | n/a | # Cookie.py is a Python module for the handling of HTTP |
|---|
| 30 | n/a | # cookies as a Python dictionary. See RFC 2109 for more |
|---|
| 31 | n/a | # information on cookies. |
|---|
| 32 | n/a | # |
|---|
| 33 | n/a | # The original idea to treat Cookies as a dictionary came from |
|---|
| 34 | n/a | # Dave Mitchell (davem@magnet.com) in 1995, when he released the |
|---|
| 35 | n/a | # first version of nscookie.py. |
|---|
| 36 | n/a | # |
|---|
| 37 | n/a | #### |
|---|
| 38 | n/a | |
|---|
| 39 | n/a | r""" |
|---|
| 40 | n/a | Here's a sample session to show how to use this module. |
|---|
| 41 | n/a | At the moment, this is the only documentation. |
|---|
| 42 | n/a | |
|---|
| 43 | n/a | The Basics |
|---|
| 44 | n/a | ---------- |
|---|
| 45 | n/a | |
|---|
| 46 | n/a | Importing is easy... |
|---|
| 47 | n/a | |
|---|
| 48 | n/a | >>> from http import cookies |
|---|
| 49 | n/a | |
|---|
| 50 | n/a | Most of the time you start by creating a cookie. |
|---|
| 51 | n/a | |
|---|
| 52 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 53 | n/a | |
|---|
| 54 | n/a | Once you've created your Cookie, you can add values just as if it were |
|---|
| 55 | n/a | a dictionary. |
|---|
| 56 | n/a | |
|---|
| 57 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 58 | n/a | >>> C["fig"] = "newton" |
|---|
| 59 | n/a | >>> C["sugar"] = "wafer" |
|---|
| 60 | n/a | >>> C.output() |
|---|
| 61 | n/a | 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer' |
|---|
| 62 | n/a | |
|---|
| 63 | n/a | Notice that the printable representation of a Cookie is the |
|---|
| 64 | n/a | appropriate format for a Set-Cookie: header. This is the |
|---|
| 65 | n/a | default behavior. You can change the header and printed |
|---|
| 66 | n/a | attributes by using the .output() function |
|---|
| 67 | n/a | |
|---|
| 68 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 69 | n/a | >>> C["rocky"] = "road" |
|---|
| 70 | n/a | >>> C["rocky"]["path"] = "/cookie" |
|---|
| 71 | n/a | >>> print(C.output(header="Cookie:")) |
|---|
| 72 | n/a | Cookie: rocky=road; Path=/cookie |
|---|
| 73 | n/a | >>> print(C.output(attrs=[], header="Cookie:")) |
|---|
| 74 | n/a | Cookie: rocky=road |
|---|
| 75 | n/a | |
|---|
| 76 | n/a | The load() method of a Cookie extracts cookies from a string. In a |
|---|
| 77 | n/a | CGI script, you would use this method to extract the cookies from the |
|---|
| 78 | n/a | HTTP_COOKIE environment variable. |
|---|
| 79 | n/a | |
|---|
| 80 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 81 | n/a | >>> C.load("chips=ahoy; vienna=finger") |
|---|
| 82 | n/a | >>> C.output() |
|---|
| 83 | n/a | 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger' |
|---|
| 84 | n/a | |
|---|
| 85 | n/a | The load() method is darn-tootin smart about identifying cookies |
|---|
| 86 | n/a | within a string. Escaped quotation marks, nested semicolons, and other |
|---|
| 87 | n/a | such trickeries do not confuse it. |
|---|
| 88 | n/a | |
|---|
| 89 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 90 | n/a | >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') |
|---|
| 91 | n/a | >>> print(C) |
|---|
| 92 | n/a | Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" |
|---|
| 93 | n/a | |
|---|
| 94 | n/a | Each element of the Cookie also supports all of the RFC 2109 |
|---|
| 95 | n/a | Cookie attributes. Here's an example which sets the Path |
|---|
| 96 | n/a | attribute. |
|---|
| 97 | n/a | |
|---|
| 98 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 99 | n/a | >>> C["oreo"] = "doublestuff" |
|---|
| 100 | n/a | >>> C["oreo"]["path"] = "/" |
|---|
| 101 | n/a | >>> print(C) |
|---|
| 102 | n/a | Set-Cookie: oreo=doublestuff; Path=/ |
|---|
| 103 | n/a | |
|---|
| 104 | n/a | Each dictionary element has a 'value' attribute, which gives you |
|---|
| 105 | n/a | back the value associated with the key. |
|---|
| 106 | n/a | |
|---|
| 107 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 108 | n/a | >>> C["twix"] = "none for you" |
|---|
| 109 | n/a | >>> C["twix"].value |
|---|
| 110 | n/a | 'none for you' |
|---|
| 111 | n/a | |
|---|
| 112 | n/a | The SimpleCookie expects that all values should be standard strings. |
|---|
| 113 | n/a | Just to be sure, SimpleCookie invokes the str() builtin to convert |
|---|
| 114 | n/a | the value to a string, when the values are set dictionary-style. |
|---|
| 115 | n/a | |
|---|
| 116 | n/a | >>> C = cookies.SimpleCookie() |
|---|
| 117 | n/a | >>> C["number"] = 7 |
|---|
| 118 | n/a | >>> C["string"] = "seven" |
|---|
| 119 | n/a | >>> C["number"].value |
|---|
| 120 | n/a | '7' |
|---|
| 121 | n/a | >>> C["string"].value |
|---|
| 122 | n/a | 'seven' |
|---|
| 123 | n/a | >>> C.output() |
|---|
| 124 | n/a | 'Set-Cookie: number=7\r\nSet-Cookie: string=seven' |
|---|
| 125 | n/a | |
|---|
| 126 | n/a | Finis. |
|---|
| 127 | n/a | """ |
|---|
| 128 | n/a | |
|---|
| 129 | n/a | # |
|---|
| 130 | n/a | # Import our required modules |
|---|
| 131 | n/a | # |
|---|
| 132 | n/a | import re |
|---|
| 133 | n/a | import string |
|---|
| 134 | n/a | |
|---|
| 135 | n/a | __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] |
|---|
| 136 | n/a | |
|---|
| 137 | n/a | _nulljoin = ''.join |
|---|
| 138 | n/a | _semispacejoin = '; '.join |
|---|
| 139 | n/a | _spacejoin = ' '.join |
|---|
| 140 | n/a | |
|---|
| 141 | n/a | # |
|---|
| 142 | n/a | # Define an exception visible to External modules |
|---|
| 143 | n/a | # |
|---|
| 144 | n/a | class CookieError(Exception): |
|---|
| 145 | n/a | pass |
|---|
| 146 | n/a | |
|---|
| 147 | n/a | |
|---|
| 148 | n/a | # These quoting routines conform to the RFC2109 specification, which in |
|---|
| 149 | n/a | # turn references the character definitions from RFC2068. They provide |
|---|
| 150 | n/a | # a two-way quoting algorithm. Any non-text character is translated |
|---|
| 151 | n/a | # into a 4 character sequence: a forward-slash followed by the |
|---|
| 152 | n/a | # three-digit octal equivalent of the character. Any '\' or '"' is |
|---|
| 153 | n/a | # quoted with a preceding '\' slash. |
|---|
| 154 | n/a | # Because of the way browsers really handle cookies (as opposed to what |
|---|
| 155 | n/a | # the RFC says) we also encode "," and ";". |
|---|
| 156 | n/a | # |
|---|
| 157 | n/a | # These are taken from RFC2068 and RFC2109. |
|---|
| 158 | n/a | # _LegalChars is the list of chars which don't require "'s |
|---|
| 159 | n/a | # _Translator hash-table for fast quoting |
|---|
| 160 | n/a | # |
|---|
| 161 | n/a | _LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:" |
|---|
| 162 | n/a | _UnescapedChars = _LegalChars + ' ()/<=>?@[]{}' |
|---|
| 163 | n/a | |
|---|
| 164 | n/a | _Translator = {n: '\\%03o' % n |
|---|
| 165 | n/a | for n in set(range(256)) - set(map(ord, _UnescapedChars))} |
|---|
| 166 | n/a | _Translator.update({ |
|---|
| 167 | n/a | ord('"'): '\\"', |
|---|
| 168 | n/a | ord('\\'): '\\\\', |
|---|
| 169 | n/a | }) |
|---|
| 170 | n/a | |
|---|
| 171 | n/a | _is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch |
|---|
| 172 | n/a | |
|---|
| 173 | n/a | def _quote(str): |
|---|
| 174 | n/a | r"""Quote a string for use in a cookie header. |
|---|
| 175 | n/a | |
|---|
| 176 | n/a | If the string does not need to be double-quoted, then just return the |
|---|
| 177 | n/a | string. Otherwise, surround the string in doublequotes and quote |
|---|
| 178 | n/a | (with a \) special characters. |
|---|
| 179 | n/a | """ |
|---|
| 180 | n/a | if str is None or _is_legal_key(str): |
|---|
| 181 | n/a | return str |
|---|
| 182 | n/a | else: |
|---|
| 183 | n/a | return '"' + str.translate(_Translator) + '"' |
|---|
| 184 | n/a | |
|---|
| 185 | n/a | |
|---|
| 186 | n/a | _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]") |
|---|
| 187 | n/a | _QuotePatt = re.compile(r"[\\].") |
|---|
| 188 | n/a | |
|---|
| 189 | n/a | def _unquote(str): |
|---|
| 190 | n/a | # If there aren't any doublequotes, |
|---|
| 191 | n/a | # then there can't be any special characters. See RFC 2109. |
|---|
| 192 | n/a | if str is None or len(str) < 2: |
|---|
| 193 | n/a | return str |
|---|
| 194 | n/a | if str[0] != '"' or str[-1] != '"': |
|---|
| 195 | n/a | return str |
|---|
| 196 | n/a | |
|---|
| 197 | n/a | # We have to assume that we must decode this string. |
|---|
| 198 | n/a | # Down to work. |
|---|
| 199 | n/a | |
|---|
| 200 | n/a | # Remove the "s |
|---|
| 201 | n/a | str = str[1:-1] |
|---|
| 202 | n/a | |
|---|
| 203 | n/a | # Check for special sequences. Examples: |
|---|
| 204 | n/a | # \012 --> \n |
|---|
| 205 | n/a | # \" --> " |
|---|
| 206 | n/a | # |
|---|
| 207 | n/a | i = 0 |
|---|
| 208 | n/a | n = len(str) |
|---|
| 209 | n/a | res = [] |
|---|
| 210 | n/a | while 0 <= i < n: |
|---|
| 211 | n/a | o_match = _OctalPatt.search(str, i) |
|---|
| 212 | n/a | q_match = _QuotePatt.search(str, i) |
|---|
| 213 | n/a | if not o_match and not q_match: # Neither matched |
|---|
| 214 | n/a | res.append(str[i:]) |
|---|
| 215 | n/a | break |
|---|
| 216 | n/a | # else: |
|---|
| 217 | n/a | j = k = -1 |
|---|
| 218 | n/a | if o_match: |
|---|
| 219 | n/a | j = o_match.start(0) |
|---|
| 220 | n/a | if q_match: |
|---|
| 221 | n/a | k = q_match.start(0) |
|---|
| 222 | n/a | if q_match and (not o_match or k < j): # QuotePatt matched |
|---|
| 223 | n/a | res.append(str[i:k]) |
|---|
| 224 | n/a | res.append(str[k+1]) |
|---|
| 225 | n/a | i = k + 2 |
|---|
| 226 | n/a | else: # OctalPatt matched |
|---|
| 227 | n/a | res.append(str[i:j]) |
|---|
| 228 | n/a | res.append(chr(int(str[j+1:j+4], 8))) |
|---|
| 229 | n/a | i = j + 4 |
|---|
| 230 | n/a | return _nulljoin(res) |
|---|
| 231 | n/a | |
|---|
| 232 | n/a | # The _getdate() routine is used to set the expiration time in the cookie's HTTP |
|---|
| 233 | n/a | # header. By default, _getdate() returns the current time in the appropriate |
|---|
| 234 | n/a | # "expires" format for a Set-Cookie header. The one optional argument is an |
|---|
| 235 | n/a | # offset from now, in seconds. For example, an offset of -3600 means "one hour |
|---|
| 236 | n/a | # ago". The offset may be a floating point number. |
|---|
| 237 | n/a | # |
|---|
| 238 | n/a | |
|---|
| 239 | n/a | _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] |
|---|
| 240 | n/a | |
|---|
| 241 | n/a | _monthname = [None, |
|---|
| 242 | n/a | 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', |
|---|
| 243 | n/a | 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] |
|---|
| 244 | n/a | |
|---|
| 245 | n/a | def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname): |
|---|
| 246 | n/a | from time import gmtime, time |
|---|
| 247 | n/a | now = time() |
|---|
| 248 | n/a | year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future) |
|---|
| 249 | n/a | return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \ |
|---|
| 250 | n/a | (weekdayname[wd], day, monthname[month], year, hh, mm, ss) |
|---|
| 251 | n/a | |
|---|
| 252 | n/a | |
|---|
| 253 | n/a | class Morsel(dict): |
|---|
| 254 | n/a | """A class to hold ONE (key, value) pair. |
|---|
| 255 | n/a | |
|---|
| 256 | n/a | In a cookie, each such pair may have several attributes, so this class is |
|---|
| 257 | n/a | used to keep the attributes associated with the appropriate key,value pair. |
|---|
| 258 | n/a | This class also includes a coded_value attribute, which is used to hold |
|---|
| 259 | n/a | the network representation of the value. This is most useful when Python |
|---|
| 260 | n/a | objects are pickled for network transit. |
|---|
| 261 | n/a | """ |
|---|
| 262 | n/a | # RFC 2109 lists these attributes as reserved: |
|---|
| 263 | n/a | # path comment domain |
|---|
| 264 | n/a | # max-age secure version |
|---|
| 265 | n/a | # |
|---|
| 266 | n/a | # For historical reasons, these attributes are also reserved: |
|---|
| 267 | n/a | # expires |
|---|
| 268 | n/a | # |
|---|
| 269 | n/a | # This is an extension from Microsoft: |
|---|
| 270 | n/a | # httponly |
|---|
| 271 | n/a | # |
|---|
| 272 | n/a | # This dictionary provides a mapping from the lowercase |
|---|
| 273 | n/a | # variant on the left to the appropriate traditional |
|---|
| 274 | n/a | # formatting on the right. |
|---|
| 275 | n/a | _reserved = { |
|---|
| 276 | n/a | "expires" : "expires", |
|---|
| 277 | n/a | "path" : "Path", |
|---|
| 278 | n/a | "comment" : "Comment", |
|---|
| 279 | n/a | "domain" : "Domain", |
|---|
| 280 | n/a | "max-age" : "Max-Age", |
|---|
| 281 | n/a | "secure" : "Secure", |
|---|
| 282 | n/a | "httponly" : "HttpOnly", |
|---|
| 283 | n/a | "version" : "Version", |
|---|
| 284 | n/a | } |
|---|
| 285 | n/a | |
|---|
| 286 | n/a | _flags = {'secure', 'httponly'} |
|---|
| 287 | n/a | |
|---|
| 288 | n/a | def __init__(self): |
|---|
| 289 | n/a | # Set defaults |
|---|
| 290 | n/a | self._key = self._value = self._coded_value = None |
|---|
| 291 | n/a | |
|---|
| 292 | n/a | # Set default attributes |
|---|
| 293 | n/a | for key in self._reserved: |
|---|
| 294 | n/a | dict.__setitem__(self, key, "") |
|---|
| 295 | n/a | |
|---|
| 296 | n/a | @property |
|---|
| 297 | n/a | def key(self): |
|---|
| 298 | n/a | return self._key |
|---|
| 299 | n/a | |
|---|
| 300 | n/a | @property |
|---|
| 301 | n/a | def value(self): |
|---|
| 302 | n/a | return self._value |
|---|
| 303 | n/a | |
|---|
| 304 | n/a | @property |
|---|
| 305 | n/a | def coded_value(self): |
|---|
| 306 | n/a | return self._coded_value |
|---|
| 307 | n/a | |
|---|
| 308 | n/a | def __setitem__(self, K, V): |
|---|
| 309 | n/a | K = K.lower() |
|---|
| 310 | n/a | if not K in self._reserved: |
|---|
| 311 | n/a | raise CookieError("Invalid attribute %r" % (K,)) |
|---|
| 312 | n/a | dict.__setitem__(self, K, V) |
|---|
| 313 | n/a | |
|---|
| 314 | n/a | def setdefault(self, key, val=None): |
|---|
| 315 | n/a | key = key.lower() |
|---|
| 316 | n/a | if key not in self._reserved: |
|---|
| 317 | n/a | raise CookieError("Invalid attribute %r" % (key,)) |
|---|
| 318 | n/a | return dict.setdefault(self, key, val) |
|---|
| 319 | n/a | |
|---|
| 320 | n/a | def __eq__(self, morsel): |
|---|
| 321 | n/a | if not isinstance(morsel, Morsel): |
|---|
| 322 | n/a | return NotImplemented |
|---|
| 323 | n/a | return (dict.__eq__(self, morsel) and |
|---|
| 324 | n/a | self._value == morsel._value and |
|---|
| 325 | n/a | self._key == morsel._key and |
|---|
| 326 | n/a | self._coded_value == morsel._coded_value) |
|---|
| 327 | n/a | |
|---|
| 328 | n/a | __ne__ = object.__ne__ |
|---|
| 329 | n/a | |
|---|
| 330 | n/a | def copy(self): |
|---|
| 331 | n/a | morsel = Morsel() |
|---|
| 332 | n/a | dict.update(morsel, self) |
|---|
| 333 | n/a | morsel.__dict__.update(self.__dict__) |
|---|
| 334 | n/a | return morsel |
|---|
| 335 | n/a | |
|---|
| 336 | n/a | def update(self, values): |
|---|
| 337 | n/a | data = {} |
|---|
| 338 | n/a | for key, val in dict(values).items(): |
|---|
| 339 | n/a | key = key.lower() |
|---|
| 340 | n/a | if key not in self._reserved: |
|---|
| 341 | n/a | raise CookieError("Invalid attribute %r" % (key,)) |
|---|
| 342 | n/a | data[key] = val |
|---|
| 343 | n/a | dict.update(self, data) |
|---|
| 344 | n/a | |
|---|
| 345 | n/a | def isReservedKey(self, K): |
|---|
| 346 | n/a | return K.lower() in self._reserved |
|---|
| 347 | n/a | |
|---|
| 348 | n/a | def set(self, key, val, coded_val): |
|---|
| 349 | n/a | if key.lower() in self._reserved: |
|---|
| 350 | n/a | raise CookieError('Attempt to set a reserved key %r' % (key,)) |
|---|
| 351 | n/a | if not _is_legal_key(key): |
|---|
| 352 | n/a | raise CookieError('Illegal key %r' % (key,)) |
|---|
| 353 | n/a | |
|---|
| 354 | n/a | # It's a good key, so save it. |
|---|
| 355 | n/a | self._key = key |
|---|
| 356 | n/a | self._value = val |
|---|
| 357 | n/a | self._coded_value = coded_val |
|---|
| 358 | n/a | |
|---|
| 359 | n/a | def __getstate__(self): |
|---|
| 360 | n/a | return { |
|---|
| 361 | n/a | 'key': self._key, |
|---|
| 362 | n/a | 'value': self._value, |
|---|
| 363 | n/a | 'coded_value': self._coded_value, |
|---|
| 364 | n/a | } |
|---|
| 365 | n/a | |
|---|
| 366 | n/a | def __setstate__(self, state): |
|---|
| 367 | n/a | self._key = state['key'] |
|---|
| 368 | n/a | self._value = state['value'] |
|---|
| 369 | n/a | self._coded_value = state['coded_value'] |
|---|
| 370 | n/a | |
|---|
| 371 | n/a | def output(self, attrs=None, header="Set-Cookie:"): |
|---|
| 372 | n/a | return "%s %s" % (header, self.OutputString(attrs)) |
|---|
| 373 | n/a | |
|---|
| 374 | n/a | __str__ = output |
|---|
| 375 | n/a | |
|---|
| 376 | n/a | def __repr__(self): |
|---|
| 377 | n/a | return '<%s: %s>' % (self.__class__.__name__, self.OutputString()) |
|---|
| 378 | n/a | |
|---|
| 379 | n/a | def js_output(self, attrs=None): |
|---|
| 380 | n/a | # Print javascript |
|---|
| 381 | n/a | return """ |
|---|
| 382 | n/a | <script type="text/javascript"> |
|---|
| 383 | n/a | <!-- begin hiding |
|---|
| 384 | n/a | document.cookie = \"%s\"; |
|---|
| 385 | n/a | // end hiding --> |
|---|
| 386 | n/a | </script> |
|---|
| 387 | n/a | """ % (self.OutputString(attrs).replace('"', r'\"')) |
|---|
| 388 | n/a | |
|---|
| 389 | n/a | def OutputString(self, attrs=None): |
|---|
| 390 | n/a | # Build up our result |
|---|
| 391 | n/a | # |
|---|
| 392 | n/a | result = [] |
|---|
| 393 | n/a | append = result.append |
|---|
| 394 | n/a | |
|---|
| 395 | n/a | # First, the key=value pair |
|---|
| 396 | n/a | append("%s=%s" % (self.key, self.coded_value)) |
|---|
| 397 | n/a | |
|---|
| 398 | n/a | # Now add any defined attributes |
|---|
| 399 | n/a | if attrs is None: |
|---|
| 400 | n/a | attrs = self._reserved |
|---|
| 401 | n/a | items = sorted(self.items()) |
|---|
| 402 | n/a | for key, value in items: |
|---|
| 403 | n/a | if value == "": |
|---|
| 404 | n/a | continue |
|---|
| 405 | n/a | if key not in attrs: |
|---|
| 406 | n/a | continue |
|---|
| 407 | n/a | if key == "expires" and isinstance(value, int): |
|---|
| 408 | n/a | append("%s=%s" % (self._reserved[key], _getdate(value))) |
|---|
| 409 | n/a | elif key == "max-age" and isinstance(value, int): |
|---|
| 410 | n/a | append("%s=%d" % (self._reserved[key], value)) |
|---|
| 411 | n/a | elif key in self._flags: |
|---|
| 412 | n/a | if value: |
|---|
| 413 | n/a | append(str(self._reserved[key])) |
|---|
| 414 | n/a | else: |
|---|
| 415 | n/a | append("%s=%s" % (self._reserved[key], value)) |
|---|
| 416 | n/a | |
|---|
| 417 | n/a | # Return the result |
|---|
| 418 | n/a | return _semispacejoin(result) |
|---|
| 419 | n/a | |
|---|
| 420 | n/a | |
|---|
| 421 | n/a | # |
|---|
| 422 | n/a | # Pattern for finding cookie |
|---|
| 423 | n/a | # |
|---|
| 424 | n/a | # This used to be strict parsing based on the RFC2109 and RFC2068 |
|---|
| 425 | n/a | # specifications. I have since discovered that MSIE 3.0x doesn't |
|---|
| 426 | n/a | # follow the character rules outlined in those specs. As a |
|---|
| 427 | n/a | # result, the parsing rules here are less strict. |
|---|
| 428 | n/a | # |
|---|
| 429 | n/a | |
|---|
| 430 | n/a | _LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=" |
|---|
| 431 | n/a | _LegalValueChars = _LegalKeyChars + r'\[\]' |
|---|
| 432 | n/a | _CookiePattern = re.compile(r""" |
|---|
| 433 | n/a | \s* # Optional whitespace at start of cookie |
|---|
| 434 | n/a | (?P<key> # Start of group 'key' |
|---|
| 435 | n/a | [""" + _LegalKeyChars + r"""]+? # Any word of at least one letter |
|---|
| 436 | n/a | ) # End of group 'key' |
|---|
| 437 | n/a | ( # Optional group: there may not be a value. |
|---|
| 438 | n/a | \s*=\s* # Equal Sign |
|---|
| 439 | n/a | (?P<val> # Start of group 'val' |
|---|
| 440 | n/a | "(?:[^\\"]|\\.)*" # Any doublequoted string |
|---|
| 441 | n/a | | # or |
|---|
| 442 | n/a | \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr |
|---|
| 443 | n/a | | # or |
|---|
| 444 | n/a | [""" + _LegalValueChars + r"""]* # Any word or empty string |
|---|
| 445 | n/a | ) # End of group 'val' |
|---|
| 446 | n/a | )? # End of optional value group |
|---|
| 447 | n/a | \s* # Any number of spaces. |
|---|
| 448 | n/a | (\s+|;|$) # Ending either at space, semicolon, or EOS. |
|---|
| 449 | n/a | """, re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe. |
|---|
| 450 | n/a | |
|---|
| 451 | n/a | |
|---|
| 452 | n/a | # At long last, here is the cookie class. Using this class is almost just like |
|---|
| 453 | n/a | # using a dictionary. See this module's docstring for example usage. |
|---|
| 454 | n/a | # |
|---|
| 455 | n/a | class BaseCookie(dict): |
|---|
| 456 | n/a | """A container class for a set of Morsels.""" |
|---|
| 457 | n/a | |
|---|
| 458 | n/a | def value_decode(self, val): |
|---|
| 459 | n/a | """real_value, coded_value = value_decode(STRING) |
|---|
| 460 | n/a | Called prior to setting a cookie's value from the network |
|---|
| 461 | n/a | representation. The VALUE is the value read from HTTP |
|---|
| 462 | n/a | header. |
|---|
| 463 | n/a | Override this function to modify the behavior of cookies. |
|---|
| 464 | n/a | """ |
|---|
| 465 | n/a | return val, val |
|---|
| 466 | n/a | |
|---|
| 467 | n/a | def value_encode(self, val): |
|---|
| 468 | n/a | """real_value, coded_value = value_encode(VALUE) |
|---|
| 469 | n/a | Called prior to setting a cookie's value from the dictionary |
|---|
| 470 | n/a | representation. The VALUE is the value being assigned. |
|---|
| 471 | n/a | Override this function to modify the behavior of cookies. |
|---|
| 472 | n/a | """ |
|---|
| 473 | n/a | strval = str(val) |
|---|
| 474 | n/a | return strval, strval |
|---|
| 475 | n/a | |
|---|
| 476 | n/a | def __init__(self, input=None): |
|---|
| 477 | n/a | if input: |
|---|
| 478 | n/a | self.load(input) |
|---|
| 479 | n/a | |
|---|
| 480 | n/a | def __set(self, key, real_value, coded_value): |
|---|
| 481 | n/a | """Private method for setting a cookie's value""" |
|---|
| 482 | n/a | M = self.get(key, Morsel()) |
|---|
| 483 | n/a | M.set(key, real_value, coded_value) |
|---|
| 484 | n/a | dict.__setitem__(self, key, M) |
|---|
| 485 | n/a | |
|---|
| 486 | n/a | def __setitem__(self, key, value): |
|---|
| 487 | n/a | """Dictionary style assignment.""" |
|---|
| 488 | n/a | if isinstance(value, Morsel): |
|---|
| 489 | n/a | # allow assignment of constructed Morsels (e.g. for pickling) |
|---|
| 490 | n/a | dict.__setitem__(self, key, value) |
|---|
| 491 | n/a | else: |
|---|
| 492 | n/a | rval, cval = self.value_encode(value) |
|---|
| 493 | n/a | self.__set(key, rval, cval) |
|---|
| 494 | n/a | |
|---|
| 495 | n/a | def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): |
|---|
| 496 | n/a | """Return a string suitable for HTTP.""" |
|---|
| 497 | n/a | result = [] |
|---|
| 498 | n/a | items = sorted(self.items()) |
|---|
| 499 | n/a | for key, value in items: |
|---|
| 500 | n/a | result.append(value.output(attrs, header)) |
|---|
| 501 | n/a | return sep.join(result) |
|---|
| 502 | n/a | |
|---|
| 503 | n/a | __str__ = output |
|---|
| 504 | n/a | |
|---|
| 505 | n/a | def __repr__(self): |
|---|
| 506 | n/a | l = [] |
|---|
| 507 | n/a | items = sorted(self.items()) |
|---|
| 508 | n/a | for key, value in items: |
|---|
| 509 | n/a | l.append('%s=%s' % (key, repr(value.value))) |
|---|
| 510 | n/a | return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l)) |
|---|
| 511 | n/a | |
|---|
| 512 | n/a | def js_output(self, attrs=None): |
|---|
| 513 | n/a | """Return a string suitable for JavaScript.""" |
|---|
| 514 | n/a | result = [] |
|---|
| 515 | n/a | items = sorted(self.items()) |
|---|
| 516 | n/a | for key, value in items: |
|---|
| 517 | n/a | result.append(value.js_output(attrs)) |
|---|
| 518 | n/a | return _nulljoin(result) |
|---|
| 519 | n/a | |
|---|
| 520 | n/a | def load(self, rawdata): |
|---|
| 521 | n/a | """Load cookies from a string (presumably HTTP_COOKIE) or |
|---|
| 522 | n/a | from a dictionary. Loading cookies from a dictionary 'd' |
|---|
| 523 | n/a | is equivalent to calling: |
|---|
| 524 | n/a | map(Cookie.__setitem__, d.keys(), d.values()) |
|---|
| 525 | n/a | """ |
|---|
| 526 | n/a | if isinstance(rawdata, str): |
|---|
| 527 | n/a | self.__parse_string(rawdata) |
|---|
| 528 | n/a | else: |
|---|
| 529 | n/a | # self.update() wouldn't call our custom __setitem__ |
|---|
| 530 | n/a | for key, value in rawdata.items(): |
|---|
| 531 | n/a | self[key] = value |
|---|
| 532 | n/a | return |
|---|
| 533 | n/a | |
|---|
| 534 | n/a | def __parse_string(self, str, patt=_CookiePattern): |
|---|
| 535 | n/a | i = 0 # Our starting point |
|---|
| 536 | n/a | n = len(str) # Length of string |
|---|
| 537 | n/a | parsed_items = [] # Parsed (type, key, value) triples |
|---|
| 538 | n/a | morsel_seen = False # A key=value pair was previously encountered |
|---|
| 539 | n/a | |
|---|
| 540 | n/a | TYPE_ATTRIBUTE = 1 |
|---|
| 541 | n/a | TYPE_KEYVALUE = 2 |
|---|
| 542 | n/a | |
|---|
| 543 | n/a | # We first parse the whole cookie string and reject it if it's |
|---|
| 544 | n/a | # syntactically invalid (this helps avoid some classes of injection |
|---|
| 545 | n/a | # attacks). |
|---|
| 546 | n/a | while 0 <= i < n: |
|---|
| 547 | n/a | # Start looking for a cookie |
|---|
| 548 | n/a | match = patt.match(str, i) |
|---|
| 549 | n/a | if not match: |
|---|
| 550 | n/a | # No more cookies |
|---|
| 551 | n/a | break |
|---|
| 552 | n/a | |
|---|
| 553 | n/a | key, value = match.group("key"), match.group("val") |
|---|
| 554 | n/a | i = match.end(0) |
|---|
| 555 | n/a | |
|---|
| 556 | n/a | if key[0] == "$": |
|---|
| 557 | n/a | if not morsel_seen: |
|---|
| 558 | n/a | # We ignore attributes which pertain to the cookie |
|---|
| 559 | n/a | # mechanism as a whole, such as "$Version". |
|---|
| 560 | n/a | # See RFC 2965. (Does anyone care?) |
|---|
| 561 | n/a | continue |
|---|
| 562 | n/a | parsed_items.append((TYPE_ATTRIBUTE, key[1:], value)) |
|---|
| 563 | n/a | elif key.lower() in Morsel._reserved: |
|---|
| 564 | n/a | if not morsel_seen: |
|---|
| 565 | n/a | # Invalid cookie string |
|---|
| 566 | n/a | return |
|---|
| 567 | n/a | if value is None: |
|---|
| 568 | n/a | if key.lower() in Morsel._flags: |
|---|
| 569 | n/a | parsed_items.append((TYPE_ATTRIBUTE, key, True)) |
|---|
| 570 | n/a | else: |
|---|
| 571 | n/a | # Invalid cookie string |
|---|
| 572 | n/a | return |
|---|
| 573 | n/a | else: |
|---|
| 574 | n/a | parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value))) |
|---|
| 575 | n/a | elif value is not None: |
|---|
| 576 | n/a | parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value))) |
|---|
| 577 | n/a | morsel_seen = True |
|---|
| 578 | n/a | else: |
|---|
| 579 | n/a | # Invalid cookie string |
|---|
| 580 | n/a | return |
|---|
| 581 | n/a | |
|---|
| 582 | n/a | # The cookie string is valid, apply it. |
|---|
| 583 | n/a | M = None # current morsel |
|---|
| 584 | n/a | for tp, key, value in parsed_items: |
|---|
| 585 | n/a | if tp == TYPE_ATTRIBUTE: |
|---|
| 586 | n/a | assert M is not None |
|---|
| 587 | n/a | M[key] = value |
|---|
| 588 | n/a | else: |
|---|
| 589 | n/a | assert tp == TYPE_KEYVALUE |
|---|
| 590 | n/a | rval, cval = value |
|---|
| 591 | n/a | self.__set(key, rval, cval) |
|---|
| 592 | n/a | M = self[key] |
|---|
| 593 | n/a | |
|---|
| 594 | n/a | |
|---|
| 595 | n/a | class SimpleCookie(BaseCookie): |
|---|
| 596 | n/a | """ |
|---|
| 597 | n/a | SimpleCookie supports strings as cookie values. When setting |
|---|
| 598 | n/a | the value using the dictionary assignment notation, SimpleCookie |
|---|
| 599 | n/a | calls the builtin str() to convert the value to a string. Values |
|---|
| 600 | n/a | received from HTTP are kept as strings. |
|---|
| 601 | n/a | """ |
|---|
| 602 | n/a | def value_decode(self, val): |
|---|
| 603 | n/a | return _unquote(val), val |
|---|
| 604 | n/a | |
|---|
| 605 | n/a | def value_encode(self, val): |
|---|
| 606 | n/a | strval = str(val) |
|---|
| 607 | n/a | return strval, _quote(strval) |
|---|