/Lib/Cookie.py

http://unladen-swallow.googlecode.com/ · Python · 752 lines · 534 code · 59 blank · 159 comment · 39 complexity · 524cdb2ebe2a4671091c4f8c27005dfd MD5 · raw file

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