You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

692 lines
24KB

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