jpayne@68: #### jpayne@68: # Copyright 2000 by Timothy O'Malley jpayne@68: # jpayne@68: # All Rights Reserved jpayne@68: # jpayne@68: # Permission to use, copy, modify, and distribute this software jpayne@68: # and its documentation for any purpose and without fee is hereby jpayne@68: # granted, provided that the above copyright notice appear in all jpayne@68: # copies and that both that copyright notice and this permission jpayne@68: # notice appear in supporting documentation, and that the name of jpayne@68: # Timothy O'Malley not be used in advertising or publicity jpayne@68: # pertaining to distribution of the software without specific, written jpayne@68: # prior permission. jpayne@68: # jpayne@68: # Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS jpayne@68: # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY jpayne@68: # AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR jpayne@68: # ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES jpayne@68: # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, jpayne@68: # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS jpayne@68: # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR jpayne@68: # PERFORMANCE OF THIS SOFTWARE. jpayne@68: # jpayne@68: #### jpayne@68: # jpayne@68: # Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp jpayne@68: # by Timothy O'Malley jpayne@68: # jpayne@68: # Cookie.py is a Python module for the handling of HTTP jpayne@68: # cookies as a Python dictionary. See RFC 2109 for more jpayne@68: # information on cookies. jpayne@68: # jpayne@68: # The original idea to treat Cookies as a dictionary came from jpayne@68: # Dave Mitchell (davem@magnet.com) in 1995, when he released the jpayne@68: # first version of nscookie.py. jpayne@68: # jpayne@68: #### jpayne@68: jpayne@68: r""" jpayne@68: Here's a sample session to show how to use this module. jpayne@68: At the moment, this is the only documentation. jpayne@68: jpayne@68: The Basics jpayne@68: ---------- jpayne@68: jpayne@68: Importing is easy... jpayne@68: jpayne@68: >>> from http import cookies jpayne@68: jpayne@68: Most of the time you start by creating a cookie. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: jpayne@68: Once you've created your Cookie, you can add values just as if it were jpayne@68: a dictionary. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C["fig"] = "newton" jpayne@68: >>> C["sugar"] = "wafer" jpayne@68: >>> C.output() jpayne@68: 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer' jpayne@68: jpayne@68: Notice that the printable representation of a Cookie is the jpayne@68: appropriate format for a Set-Cookie: header. This is the jpayne@68: default behavior. You can change the header and printed jpayne@68: attributes by using the .output() function jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C["rocky"] = "road" jpayne@68: >>> C["rocky"]["path"] = "/cookie" jpayne@68: >>> print(C.output(header="Cookie:")) jpayne@68: Cookie: rocky=road; Path=/cookie jpayne@68: >>> print(C.output(attrs=[], header="Cookie:")) jpayne@68: Cookie: rocky=road jpayne@68: jpayne@68: The load() method of a Cookie extracts cookies from a string. In a jpayne@68: CGI script, you would use this method to extract the cookies from the jpayne@68: HTTP_COOKIE environment variable. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C.load("chips=ahoy; vienna=finger") jpayne@68: >>> C.output() jpayne@68: 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger' jpayne@68: jpayne@68: The load() method is darn-tootin smart about identifying cookies jpayne@68: within a string. Escaped quotation marks, nested semicolons, and other jpayne@68: such trickeries do not confuse it. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') jpayne@68: >>> print(C) jpayne@68: Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" jpayne@68: jpayne@68: Each element of the Cookie also supports all of the RFC 2109 jpayne@68: Cookie attributes. Here's an example which sets the Path jpayne@68: attribute. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C["oreo"] = "doublestuff" jpayne@68: >>> C["oreo"]["path"] = "/" jpayne@68: >>> print(C) jpayne@68: Set-Cookie: oreo=doublestuff; Path=/ jpayne@68: jpayne@68: Each dictionary element has a 'value' attribute, which gives you jpayne@68: back the value associated with the key. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C["twix"] = "none for you" jpayne@68: >>> C["twix"].value jpayne@68: 'none for you' jpayne@68: jpayne@68: The SimpleCookie expects that all values should be standard strings. jpayne@68: Just to be sure, SimpleCookie invokes the str() builtin to convert jpayne@68: the value to a string, when the values are set dictionary-style. jpayne@68: jpayne@68: >>> C = cookies.SimpleCookie() jpayne@68: >>> C["number"] = 7 jpayne@68: >>> C["string"] = "seven" jpayne@68: >>> C["number"].value jpayne@68: '7' jpayne@68: >>> C["string"].value jpayne@68: 'seven' jpayne@68: >>> C.output() jpayne@68: 'Set-Cookie: number=7\r\nSet-Cookie: string=seven' jpayne@68: jpayne@68: Finis. jpayne@68: """ jpayne@68: jpayne@68: # jpayne@68: # Import our required modules jpayne@68: # jpayne@68: import re jpayne@68: import string jpayne@68: jpayne@68: __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] jpayne@68: jpayne@68: _nulljoin = ''.join jpayne@68: _semispacejoin = '; '.join jpayne@68: _spacejoin = ' '.join jpayne@68: jpayne@68: # jpayne@68: # Define an exception visible to External modules jpayne@68: # jpayne@68: class CookieError(Exception): jpayne@68: pass jpayne@68: jpayne@68: jpayne@68: # These quoting routines conform to the RFC2109 specification, which in jpayne@68: # turn references the character definitions from RFC2068. They provide jpayne@68: # a two-way quoting algorithm. Any non-text character is translated jpayne@68: # into a 4 character sequence: a forward-slash followed by the jpayne@68: # three-digit octal equivalent of the character. Any '\' or '"' is jpayne@68: # quoted with a preceding '\' slash. jpayne@68: # Because of the way browsers really handle cookies (as opposed to what jpayne@68: # the RFC says) we also encode "," and ";". jpayne@68: # jpayne@68: # These are taken from RFC2068 and RFC2109. jpayne@68: # _LegalChars is the list of chars which don't require "'s jpayne@68: # _Translator hash-table for fast quoting jpayne@68: # jpayne@68: _LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~:" jpayne@68: _UnescapedChars = _LegalChars + ' ()/<=>?@[]{}' jpayne@68: jpayne@68: _Translator = {n: '\\%03o' % n jpayne@68: for n in set(range(256)) - set(map(ord, _UnescapedChars))} jpayne@68: _Translator.update({ jpayne@68: ord('"'): '\\"', jpayne@68: ord('\\'): '\\\\', jpayne@68: }) jpayne@68: jpayne@68: _is_legal_key = re.compile('[%s]+' % re.escape(_LegalChars)).fullmatch jpayne@68: jpayne@68: def _quote(str): jpayne@68: r"""Quote a string for use in a cookie header. jpayne@68: jpayne@68: If the string does not need to be double-quoted, then just return the jpayne@68: string. Otherwise, surround the string in doublequotes and quote jpayne@68: (with a \) special characters. jpayne@68: """ jpayne@68: if str is None or _is_legal_key(str): jpayne@68: return str jpayne@68: else: jpayne@68: return '"' + str.translate(_Translator) + '"' jpayne@68: jpayne@68: jpayne@68: _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]") jpayne@68: _QuotePatt = re.compile(r"[\\].") jpayne@68: jpayne@68: def _unquote(str): jpayne@68: # If there aren't any doublequotes, jpayne@68: # then there can't be any special characters. See RFC 2109. jpayne@68: if str is None or len(str) < 2: jpayne@68: return str jpayne@68: if str[0] != '"' or str[-1] != '"': jpayne@68: return str jpayne@68: jpayne@68: # We have to assume that we must decode this string. jpayne@68: # Down to work. jpayne@68: jpayne@68: # Remove the "s jpayne@68: str = str[1:-1] jpayne@68: jpayne@68: # Check for special sequences. Examples: jpayne@68: # \012 --> \n jpayne@68: # \" --> " jpayne@68: # jpayne@68: i = 0 jpayne@68: n = len(str) jpayne@68: res = [] jpayne@68: while 0 <= i < n: jpayne@68: o_match = _OctalPatt.search(str, i) jpayne@68: q_match = _QuotePatt.search(str, i) jpayne@68: if not o_match and not q_match: # Neither matched jpayne@68: res.append(str[i:]) jpayne@68: break jpayne@68: # else: jpayne@68: j = k = -1 jpayne@68: if o_match: jpayne@68: j = o_match.start(0) jpayne@68: if q_match: jpayne@68: k = q_match.start(0) jpayne@68: if q_match and (not o_match or k < j): # QuotePatt matched jpayne@68: res.append(str[i:k]) jpayne@68: res.append(str[k+1]) jpayne@68: i = k + 2 jpayne@68: else: # OctalPatt matched jpayne@68: res.append(str[i:j]) jpayne@68: res.append(chr(int(str[j+1:j+4], 8))) jpayne@68: i = j + 4 jpayne@68: return _nulljoin(res) jpayne@68: jpayne@68: # The _getdate() routine is used to set the expiration time in the cookie's HTTP jpayne@68: # header. By default, _getdate() returns the current time in the appropriate jpayne@68: # "expires" format for a Set-Cookie header. The one optional argument is an jpayne@68: # offset from now, in seconds. For example, an offset of -3600 means "one hour jpayne@68: # ago". The offset may be a floating point number. jpayne@68: # jpayne@68: jpayne@68: _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] jpayne@68: jpayne@68: _monthname = [None, jpayne@68: 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', jpayne@68: 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] jpayne@68: jpayne@68: def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname): jpayne@68: from time import gmtime, time jpayne@68: now = time() jpayne@68: year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future) jpayne@68: return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \ jpayne@68: (weekdayname[wd], day, monthname[month], year, hh, mm, ss) jpayne@68: jpayne@68: jpayne@68: class Morsel(dict): jpayne@68: """A class to hold ONE (key, value) pair. jpayne@68: jpayne@68: In a cookie, each such pair may have several attributes, so this class is jpayne@68: used to keep the attributes associated with the appropriate key,value pair. jpayne@68: This class also includes a coded_value attribute, which is used to hold jpayne@68: the network representation of the value. jpayne@68: """ jpayne@68: # RFC 2109 lists these attributes as reserved: jpayne@68: # path comment domain jpayne@68: # max-age secure version jpayne@68: # jpayne@68: # For historical reasons, these attributes are also reserved: jpayne@68: # expires jpayne@68: # jpayne@68: # This is an extension from Microsoft: jpayne@68: # httponly jpayne@68: # jpayne@68: # This dictionary provides a mapping from the lowercase jpayne@68: # variant on the left to the appropriate traditional jpayne@68: # formatting on the right. jpayne@68: _reserved = { jpayne@68: "expires" : "expires", jpayne@68: "path" : "Path", jpayne@68: "comment" : "Comment", jpayne@68: "domain" : "Domain", jpayne@68: "max-age" : "Max-Age", jpayne@68: "secure" : "Secure", jpayne@68: "httponly" : "HttpOnly", jpayne@68: "version" : "Version", jpayne@68: "samesite" : "SameSite", jpayne@68: } jpayne@68: jpayne@68: _flags = {'secure', 'httponly'} jpayne@68: jpayne@68: def __init__(self): jpayne@68: # Set defaults jpayne@68: self._key = self._value = self._coded_value = None jpayne@68: jpayne@68: # Set default attributes jpayne@68: for key in self._reserved: jpayne@68: dict.__setitem__(self, key, "") jpayne@68: jpayne@68: @property jpayne@68: def key(self): jpayne@68: return self._key jpayne@68: jpayne@68: @property jpayne@68: def value(self): jpayne@68: return self._value jpayne@68: jpayne@68: @property jpayne@68: def coded_value(self): jpayne@68: return self._coded_value jpayne@68: jpayne@68: def __setitem__(self, K, V): jpayne@68: K = K.lower() jpayne@68: if not K in self._reserved: jpayne@68: raise CookieError("Invalid attribute %r" % (K,)) jpayne@68: dict.__setitem__(self, K, V) jpayne@68: jpayne@68: def setdefault(self, key, val=None): jpayne@68: key = key.lower() jpayne@68: if key not in self._reserved: jpayne@68: raise CookieError("Invalid attribute %r" % (key,)) jpayne@68: return dict.setdefault(self, key, val) jpayne@68: jpayne@68: def __eq__(self, morsel): jpayne@68: if not isinstance(morsel, Morsel): jpayne@68: return NotImplemented jpayne@68: return (dict.__eq__(self, morsel) and jpayne@68: self._value == morsel._value and jpayne@68: self._key == morsel._key and jpayne@68: self._coded_value == morsel._coded_value) jpayne@68: jpayne@68: __ne__ = object.__ne__ jpayne@68: jpayne@68: def copy(self): jpayne@68: morsel = Morsel() jpayne@68: dict.update(morsel, self) jpayne@68: morsel.__dict__.update(self.__dict__) jpayne@68: return morsel jpayne@68: jpayne@68: def update(self, values): jpayne@68: data = {} jpayne@68: for key, val in dict(values).items(): jpayne@68: key = key.lower() jpayne@68: if key not in self._reserved: jpayne@68: raise CookieError("Invalid attribute %r" % (key,)) jpayne@68: data[key] = val jpayne@68: dict.update(self, data) jpayne@68: jpayne@68: def isReservedKey(self, K): jpayne@68: return K.lower() in self._reserved jpayne@68: jpayne@68: def set(self, key, val, coded_val): jpayne@68: if key.lower() in self._reserved: jpayne@68: raise CookieError('Attempt to set a reserved key %r' % (key,)) jpayne@68: if not _is_legal_key(key): jpayne@68: raise CookieError('Illegal key %r' % (key,)) jpayne@68: jpayne@68: # It's a good key, so save it. jpayne@68: self._key = key jpayne@68: self._value = val jpayne@68: self._coded_value = coded_val jpayne@68: jpayne@68: def __getstate__(self): jpayne@68: return { jpayne@68: 'key': self._key, jpayne@68: 'value': self._value, jpayne@68: 'coded_value': self._coded_value, jpayne@68: } jpayne@68: jpayne@68: def __setstate__(self, state): jpayne@68: self._key = state['key'] jpayne@68: self._value = state['value'] jpayne@68: self._coded_value = state['coded_value'] jpayne@68: jpayne@68: def output(self, attrs=None, header="Set-Cookie:"): jpayne@68: return "%s %s" % (header, self.OutputString(attrs)) jpayne@68: jpayne@68: __str__ = output jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return '<%s: %s>' % (self.__class__.__name__, self.OutputString()) jpayne@68: jpayne@68: def js_output(self, attrs=None): jpayne@68: # Print javascript jpayne@68: return """ jpayne@68: jpayne@68: """ % (self.OutputString(attrs).replace('"', r'\"')) jpayne@68: jpayne@68: def OutputString(self, attrs=None): jpayne@68: # Build up our result jpayne@68: # jpayne@68: result = [] jpayne@68: append = result.append jpayne@68: jpayne@68: # First, the key=value pair jpayne@68: append("%s=%s" % (self.key, self.coded_value)) jpayne@68: jpayne@68: # Now add any defined attributes jpayne@68: if attrs is None: jpayne@68: attrs = self._reserved jpayne@68: items = sorted(self.items()) jpayne@68: for key, value in items: jpayne@68: if value == "": jpayne@68: continue jpayne@68: if key not in attrs: jpayne@68: continue jpayne@68: if key == "expires" and isinstance(value, int): jpayne@68: append("%s=%s" % (self._reserved[key], _getdate(value))) jpayne@68: elif key == "max-age" and isinstance(value, int): jpayne@68: append("%s=%d" % (self._reserved[key], value)) jpayne@68: elif key == "comment" and isinstance(value, str): jpayne@68: append("%s=%s" % (self._reserved[key], _quote(value))) jpayne@68: elif key in self._flags: jpayne@68: if value: jpayne@68: append(str(self._reserved[key])) jpayne@68: else: jpayne@68: append("%s=%s" % (self._reserved[key], value)) jpayne@68: jpayne@68: # Return the result jpayne@68: return _semispacejoin(result) jpayne@68: jpayne@68: jpayne@68: # jpayne@68: # Pattern for finding cookie jpayne@68: # jpayne@68: # This used to be strict parsing based on the RFC2109 and RFC2068 jpayne@68: # specifications. I have since discovered that MSIE 3.0x doesn't jpayne@68: # follow the character rules outlined in those specs. As a jpayne@68: # result, the parsing rules here are less strict. jpayne@68: # jpayne@68: jpayne@68: _LegalKeyChars = r"\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=" jpayne@68: _LegalValueChars = _LegalKeyChars + r'\[\]' jpayne@68: _CookiePattern = re.compile(r""" jpayne@68: \s* # Optional whitespace at start of cookie jpayne@68: (?P # Start of group 'key' jpayne@68: [""" + _LegalKeyChars + r"""]+? # Any word of at least one letter jpayne@68: ) # End of group 'key' jpayne@68: ( # Optional group: there may not be a value. jpayne@68: \s*=\s* # Equal Sign jpayne@68: (?P # Start of group 'val' jpayne@68: "(?:[^\\"]|\\.)*" # Any doublequoted string jpayne@68: | # or jpayne@68: \w{3},\s[\w\d\s-]{9,11}\s[\d:]{8}\sGMT # Special case for "expires" attr jpayne@68: | # or jpayne@68: [""" + _LegalValueChars + r"""]* # Any word or empty string jpayne@68: ) # End of group 'val' jpayne@68: )? # End of optional value group jpayne@68: \s* # Any number of spaces. jpayne@68: (\s+|;|$) # Ending either at space, semicolon, or EOS. jpayne@68: """, re.ASCII | re.VERBOSE) # re.ASCII may be removed if safe. jpayne@68: jpayne@68: jpayne@68: # At long last, here is the cookie class. Using this class is almost just like jpayne@68: # using a dictionary. See this module's docstring for example usage. jpayne@68: # jpayne@68: class BaseCookie(dict): jpayne@68: """A container class for a set of Morsels.""" jpayne@68: jpayne@68: def value_decode(self, val): jpayne@68: """real_value, coded_value = value_decode(STRING) jpayne@68: Called prior to setting a cookie's value from the network jpayne@68: representation. The VALUE is the value read from HTTP jpayne@68: header. jpayne@68: Override this function to modify the behavior of cookies. jpayne@68: """ jpayne@68: return val, val jpayne@68: jpayne@68: def value_encode(self, val): jpayne@68: """real_value, coded_value = value_encode(VALUE) jpayne@68: Called prior to setting a cookie's value from the dictionary jpayne@68: representation. The VALUE is the value being assigned. jpayne@68: Override this function to modify the behavior of cookies. jpayne@68: """ jpayne@68: strval = str(val) jpayne@68: return strval, strval jpayne@68: jpayne@68: def __init__(self, input=None): jpayne@68: if input: jpayne@68: self.load(input) jpayne@68: jpayne@68: def __set(self, key, real_value, coded_value): jpayne@68: """Private method for setting a cookie's value""" jpayne@68: M = self.get(key, Morsel()) jpayne@68: M.set(key, real_value, coded_value) jpayne@68: dict.__setitem__(self, key, M) jpayne@68: jpayne@68: def __setitem__(self, key, value): jpayne@68: """Dictionary style assignment.""" jpayne@68: if isinstance(value, Morsel): jpayne@68: # allow assignment of constructed Morsels (e.g. for pickling) jpayne@68: dict.__setitem__(self, key, value) jpayne@68: else: jpayne@68: rval, cval = self.value_encode(value) jpayne@68: self.__set(key, rval, cval) jpayne@68: jpayne@68: def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): jpayne@68: """Return a string suitable for HTTP.""" jpayne@68: result = [] jpayne@68: items = sorted(self.items()) jpayne@68: for key, value in items: jpayne@68: result.append(value.output(attrs, header)) jpayne@68: return sep.join(result) jpayne@68: jpayne@68: __str__ = output jpayne@68: jpayne@68: def __repr__(self): jpayne@68: l = [] jpayne@68: items = sorted(self.items()) jpayne@68: for key, value in items: jpayne@68: l.append('%s=%s' % (key, repr(value.value))) jpayne@68: return '<%s: %s>' % (self.__class__.__name__, _spacejoin(l)) jpayne@68: jpayne@68: def js_output(self, attrs=None): jpayne@68: """Return a string suitable for JavaScript.""" jpayne@68: result = [] jpayne@68: items = sorted(self.items()) jpayne@68: for key, value in items: jpayne@68: result.append(value.js_output(attrs)) jpayne@68: return _nulljoin(result) jpayne@68: jpayne@68: def load(self, rawdata): jpayne@68: """Load cookies from a string (presumably HTTP_COOKIE) or jpayne@68: from a dictionary. Loading cookies from a dictionary 'd' jpayne@68: is equivalent to calling: jpayne@68: map(Cookie.__setitem__, d.keys(), d.values()) jpayne@68: """ jpayne@68: if isinstance(rawdata, str): jpayne@68: self.__parse_string(rawdata) jpayne@68: else: jpayne@68: # self.update() wouldn't call our custom __setitem__ jpayne@68: for key, value in rawdata.items(): jpayne@68: self[key] = value jpayne@68: return jpayne@68: jpayne@68: def __parse_string(self, str, patt=_CookiePattern): jpayne@68: i = 0 # Our starting point jpayne@68: n = len(str) # Length of string jpayne@68: parsed_items = [] # Parsed (type, key, value) triples jpayne@68: morsel_seen = False # A key=value pair was previously encountered jpayne@68: jpayne@68: TYPE_ATTRIBUTE = 1 jpayne@68: TYPE_KEYVALUE = 2 jpayne@68: jpayne@68: # We first parse the whole cookie string and reject it if it's jpayne@68: # syntactically invalid (this helps avoid some classes of injection jpayne@68: # attacks). jpayne@68: while 0 <= i < n: jpayne@68: # Start looking for a cookie jpayne@68: match = patt.match(str, i) jpayne@68: if not match: jpayne@68: # No more cookies jpayne@68: break jpayne@68: jpayne@68: key, value = match.group("key"), match.group("val") jpayne@68: i = match.end(0) jpayne@68: jpayne@68: if key[0] == "$": jpayne@68: if not morsel_seen: jpayne@68: # We ignore attributes which pertain to the cookie jpayne@68: # mechanism as a whole, such as "$Version". jpayne@68: # See RFC 2965. (Does anyone care?) jpayne@68: continue jpayne@68: parsed_items.append((TYPE_ATTRIBUTE, key[1:], value)) jpayne@68: elif key.lower() in Morsel._reserved: jpayne@68: if not morsel_seen: jpayne@68: # Invalid cookie string jpayne@68: return jpayne@68: if value is None: jpayne@68: if key.lower() in Morsel._flags: jpayne@68: parsed_items.append((TYPE_ATTRIBUTE, key, True)) jpayne@68: else: jpayne@68: # Invalid cookie string jpayne@68: return jpayne@68: else: jpayne@68: parsed_items.append((TYPE_ATTRIBUTE, key, _unquote(value))) jpayne@68: elif value is not None: jpayne@68: parsed_items.append((TYPE_KEYVALUE, key, self.value_decode(value))) jpayne@68: morsel_seen = True jpayne@68: else: jpayne@68: # Invalid cookie string jpayne@68: return jpayne@68: jpayne@68: # The cookie string is valid, apply it. jpayne@68: M = None # current morsel jpayne@68: for tp, key, value in parsed_items: jpayne@68: if tp == TYPE_ATTRIBUTE: jpayne@68: assert M is not None jpayne@68: M[key] = value jpayne@68: else: jpayne@68: assert tp == TYPE_KEYVALUE jpayne@68: rval, cval = value jpayne@68: self.__set(key, rval, cval) jpayne@68: M = self[key] jpayne@68: jpayne@68: jpayne@68: class SimpleCookie(BaseCookie): jpayne@68: """ jpayne@68: SimpleCookie supports strings as cookie values. When setting jpayne@68: the value using the dictionary assignment notation, SimpleCookie jpayne@68: calls the builtin str() to convert the value to a string. Values jpayne@68: received from HTTP are kept as strings. jpayne@68: """ jpayne@68: def value_decode(self, val): jpayne@68: return _unquote(val), val jpayne@68: jpayne@68: def value_encode(self, val): jpayne@68: strval = str(val) jpayne@68: return strval, _quote(strval)