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