annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/http/cookies.py @ 69:33d812a61356

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