PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/Cookie.py

https://bitbucket.org/evelyn559/pypy
Python | 761 lines | 612 code | 51 blank | 98 comment | 22 complexity | cb7554a4e9ef4c902fe03ac0c64baa17 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\'\\012p1\\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. # Because of the way browsers really handle cookies (as opposed
  212. # to what the RFC says) we also encode , and ;
  213. ',' : '\\054', ';' : '\\073',
  214. '"' : '\\"', '\\' : '\\\\',
  215. '\177' : '\\177', '\200' : '\\200', '\201' : '\\201',
  216. '\202' : '\\202', '\203' : '\\203', '\204' : '\\204',
  217. '\205' : '\\205', '\206' : '\\206', '\207' : '\\207',
  218. '\210' : '\\210', '\211' : '\\211', '\212' : '\\212',
  219. '\213' : '\\213', '\214' : '\\214', '\215' : '\\215',
  220. '\216' : '\\216', '\217' : '\\217', '\220' : '\\220',
  221. '\221' : '\\221', '\222' : '\\222', '\223' : '\\223',
  222. '\224' : '\\224', '\225' : '\\225', '\226' : '\\226',
  223. '\227' : '\\227', '\230' : '\\230', '\231' : '\\231',
  224. '\232' : '\\232', '\233' : '\\233', '\234' : '\\234',
  225. '\235' : '\\235', '\236' : '\\236', '\237' : '\\237',
  226. '\240' : '\\240', '\241' : '\\241', '\242' : '\\242',
  227. '\243' : '\\243', '\244' : '\\244', '\245' : '\\245',
  228. '\246' : '\\246', '\247' : '\\247', '\250' : '\\250',
  229. '\251' : '\\251', '\252' : '\\252', '\253' : '\\253',
  230. '\254' : '\\254', '\255' : '\\255', '\256' : '\\256',
  231. '\257' : '\\257', '\260' : '\\260', '\261' : '\\261',
  232. '\262' : '\\262', '\263' : '\\263', '\264' : '\\264',
  233. '\265' : '\\265', '\266' : '\\266', '\267' : '\\267',
  234. '\270' : '\\270', '\271' : '\\271', '\272' : '\\272',
  235. '\273' : '\\273', '\274' : '\\274', '\275' : '\\275',
  236. '\276' : '\\276', '\277' : '\\277', '\300' : '\\300',
  237. '\301' : '\\301', '\302' : '\\302', '\303' : '\\303',
  238. '\304' : '\\304', '\305' : '\\305', '\306' : '\\306',
  239. '\307' : '\\307', '\310' : '\\310', '\311' : '\\311',
  240. '\312' : '\\312', '\313' : '\\313', '\314' : '\\314',
  241. '\315' : '\\315', '\316' : '\\316', '\317' : '\\317',
  242. '\320' : '\\320', '\321' : '\\321', '\322' : '\\322',
  243. '\323' : '\\323', '\324' : '\\324', '\325' : '\\325',
  244. '\326' : '\\326', '\327' : '\\327', '\330' : '\\330',
  245. '\331' : '\\331', '\332' : '\\332', '\333' : '\\333',
  246. '\334' : '\\334', '\335' : '\\335', '\336' : '\\336',
  247. '\337' : '\\337', '\340' : '\\340', '\341' : '\\341',
  248. '\342' : '\\342', '\343' : '\\343', '\344' : '\\344',
  249. '\345' : '\\345', '\346' : '\\346', '\347' : '\\347',
  250. '\350' : '\\350', '\351' : '\\351', '\352' : '\\352',
  251. '\353' : '\\353', '\354' : '\\354', '\355' : '\\355',
  252. '\356' : '\\356', '\357' : '\\357', '\360' : '\\360',
  253. '\361' : '\\361', '\362' : '\\362', '\363' : '\\363',
  254. '\364' : '\\364', '\365' : '\\365', '\366' : '\\366',
  255. '\367' : '\\367', '\370' : '\\370', '\371' : '\\371',
  256. '\372' : '\\372', '\373' : '\\373', '\374' : '\\374',
  257. '\375' : '\\375', '\376' : '\\376', '\377' : '\\377'
  258. }
  259. _idmap = ''.join(chr(x) for x in xrange(256))
  260. def _quote(str, LegalChars=_LegalChars,
  261. idmap=_idmap, translate=string.translate):
  262. #
  263. # If the string does not need to be double-quoted,
  264. # then just return the string. Otherwise, surround
  265. # the string in doublequotes and precede quote (with a \)
  266. # special characters.
  267. #
  268. if "" == translate(str, idmap, LegalChars):
  269. return str
  270. else:
  271. return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'
  272. # end _quote
  273. _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")
  274. _QuotePatt = re.compile(r"[\\].")
  275. def _unquote(str):
  276. # If there aren't any doublequotes,
  277. # then there can't be any special characters. See RFC 2109.
  278. if len(str) < 2:
  279. return str
  280. if str[0] != '"' or str[-1] != '"':
  281. return str
  282. # We have to assume that we must decode this string.
  283. # Down to work.
  284. # Remove the "s
  285. str = str[1:-1]
  286. # Check for special sequences. Examples:
  287. # \012 --> \n
  288. # \" --> "
  289. #
  290. i = 0
  291. n = len(str)
  292. res = []
  293. while 0 <= i < n:
  294. Omatch = _OctalPatt.search(str, i)
  295. Qmatch = _QuotePatt.search(str, i)
  296. if not Omatch and not Qmatch: # Neither matched
  297. res.append(str[i:])
  298. break
  299. # else:
  300. j = k = -1
  301. if Omatch: j = Omatch.start(0)
  302. if Qmatch: k = Qmatch.start(0)
  303. if Qmatch and ( not Omatch or k < j ): # QuotePatt matched
  304. res.append(str[i:k])
  305. res.append(str[k+1])
  306. i = k+2
  307. else: # OctalPatt matched
  308. res.append(str[i:j])
  309. res.append( chr( int(str[j+1:j+4], 8) ) )
  310. i = j+4
  311. return _nulljoin(res)
  312. # end _unquote
  313. # The _getdate() routine is used to set the expiration time in
  314. # the cookie's HTTP header. By default, _getdate() returns the
  315. # current time in the appropriate "expires" format for a
  316. # Set-Cookie header. The one optional argument is an offset from
  317. # now, in seconds. For example, an offset of -3600 means "one hour ago".
  318. # The offset may be a floating point number.
  319. #
  320. _weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  321. _monthname = [None,
  322. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  323. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  324. def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
  325. from time import gmtime, time
  326. now = time()
  327. year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
  328. return "%s, %02d-%3s-%4d %02d:%02d:%02d GMT" % \
  329. (weekdayname[wd], day, monthname[month], year, hh, mm, ss)
  330. #
  331. # A class to hold ONE key,value pair.
  332. # In a cookie, each such pair may have several attributes.
  333. # so this class is used to keep the attributes associated
  334. # with the appropriate key,value pair.
  335. # This class also includes a coded_value attribute, which
  336. # is used to hold the network representation of the
  337. # value. This is most useful when Python objects are
  338. # pickled for network transit.
  339. #
  340. class Morsel(dict):
  341. # RFC 2109 lists these attributes as reserved:
  342. # path comment domain
  343. # max-age secure version
  344. #
  345. # For historical reasons, these attributes are also reserved:
  346. # expires
  347. #
  348. # This is an extension from Microsoft:
  349. # httponly
  350. #
  351. # This dictionary provides a mapping from the lowercase
  352. # variant on the left to the appropriate traditional
  353. # formatting on the right.
  354. _reserved = { "expires" : "expires",
  355. "path" : "Path",
  356. "comment" : "Comment",
  357. "domain" : "Domain",
  358. "max-age" : "Max-Age",
  359. "secure" : "secure",
  360. "httponly" : "httponly",
  361. "version" : "Version",
  362. }
  363. def __init__(self):
  364. # Set defaults
  365. self.key = self.value = self.coded_value = None
  366. # Set default attributes
  367. for K in self._reserved:
  368. dict.__setitem__(self, K, "")
  369. # end __init__
  370. def __setitem__(self, K, V):
  371. K = K.lower()
  372. if not K in self._reserved:
  373. raise CookieError("Invalid Attribute %s" % K)
  374. dict.__setitem__(self, K, V)
  375. # end __setitem__
  376. def isReservedKey(self, K):
  377. return K.lower() in self._reserved
  378. # end isReservedKey
  379. def set(self, key, val, coded_val,
  380. LegalChars=_LegalChars,
  381. idmap=_idmap, translate=string.translate):
  382. # First we verify that the key isn't a reserved word
  383. # Second we make sure it only contains legal characters
  384. if key.lower() in self._reserved:
  385. raise CookieError("Attempt to set a reserved key: %s" % key)
  386. if "" != translate(key, idmap, LegalChars):
  387. raise CookieError("Illegal key value: %s" % key)
  388. # It's a good key, so save it.
  389. self.key = key
  390. self.value = val
  391. self.coded_value = coded_val
  392. # end set
  393. def output(self, attrs=None, header = "Set-Cookie:"):
  394. return "%s %s" % ( header, self.OutputString(attrs) )
  395. __str__ = output
  396. def __repr__(self):
  397. return '<%s: %s=%s>' % (self.__class__.__name__,
  398. self.key, repr(self.value) )
  399. def js_output(self, attrs=None):
  400. # Print javascript
  401. return """
  402. <script type="text/javascript">
  403. <!-- begin hiding
  404. document.cookie = \"%s\";
  405. // end hiding -->
  406. </script>
  407. """ % ( self.OutputString(attrs).replace('"',r'\"'), )
  408. # end js_output()
  409. def OutputString(self, attrs=None):
  410. # Build up our result
  411. #
  412. result = []
  413. RA = result.append
  414. # First, the key=value pair
  415. RA("%s=%s" % (self.key, self.coded_value))
  416. # Now add any defined attributes
  417. if attrs is None:
  418. attrs = self._reserved
  419. items = self.items()
  420. items.sort()
  421. for K,V in items:
  422. if V == "": continue
  423. if K not in attrs: continue
  424. if K == "expires" and type(V) == type(1):
  425. RA("%s=%s" % (self._reserved[K], _getdate(V)))
  426. elif K == "max-age" and type(V) == type(1):
  427. RA("%s=%d" % (self._reserved[K], V))
  428. elif K == "secure":
  429. RA(str(self._reserved[K]))
  430. elif K == "httponly":
  431. RA(str(self._reserved[K]))
  432. else:
  433. RA("%s=%s" % (self._reserved[K], V))
  434. # Return the result
  435. return _semispacejoin(result)
  436. # end OutputString
  437. # end Morsel class
  438. #
  439. # Pattern for finding cookie
  440. #
  441. # This used to be strict parsing based on the RFC2109 and RFC2068
  442. # specifications. I have since discovered that MSIE 3.0x doesn't
  443. # follow the character rules outlined in those specs. As a
  444. # result, the parsing rules here are less strict.
  445. #
  446. _LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=]"
  447. _CookiePattern = re.compile(
  448. r"(?x)" # This is a Verbose pattern
  449. r"(?P<key>" # Start of group 'key'
  450. ""+ _LegalCharsPatt +"+?" # Any word of at least one letter, nongreedy
  451. r")" # End of group 'key'
  452. r"\s*=\s*" # Equal Sign
  453. r"(?P<val>" # Start of group 'val'
  454. r'"(?:[^\\"]|\\.)*"' # Any doublequoted string
  455. r"|" # or
  456. r"\w{3},\s[\w\d-]{9,11}\s[\d:]{8}\sGMT" # Special case for "expires" attr
  457. r"|" # or
  458. ""+ _LegalCharsPatt +"*" # Any word or empty string
  459. r")" # End of group 'val'
  460. r"\s*;?" # Probably ending in a semi-colon
  461. )
  462. # At long last, here is the cookie class.
  463. # Using this class is almost just like using a dictionary.
  464. # See this module's docstring for example usage.
  465. #
  466. class BaseCookie(dict):
  467. # A container class for a set of Morsels
  468. #
  469. def value_decode(self, val):
  470. """real_value, coded_value = value_decode(STRING)
  471. Called prior to setting a cookie's value from the network
  472. representation. The VALUE is the value read from HTTP
  473. header.
  474. Override this function to modify the behavior of cookies.
  475. """
  476. return val, val
  477. # end value_encode
  478. def value_encode(self, val):
  479. """real_value, coded_value = value_encode(VALUE)
  480. Called prior to setting a cookie's value from the dictionary
  481. representation. The VALUE is the value being assigned.
  482. Override this function to modify the behavior of cookies.
  483. """
  484. strval = str(val)
  485. return strval, strval
  486. # end value_encode
  487. def __init__(self, input=None):
  488. if input: self.load(input)
  489. # end __init__
  490. def __set(self, key, real_value, coded_value):
  491. """Private method for setting a cookie's value"""
  492. M = self.get(key, Morsel())
  493. M.set(key, real_value, coded_value)
  494. dict.__setitem__(self, key, M)
  495. # end __set
  496. def __setitem__(self, key, value):
  497. """Dictionary style assignment."""
  498. rval, cval = self.value_encode(value)
  499. self.__set(key, rval, cval)
  500. # end __setitem__
  501. def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
  502. """Return a string suitable for HTTP."""
  503. result = []
  504. items = self.items()
  505. items.sort()
  506. for K,V in items:
  507. result.append( V.output(attrs, header) )
  508. return sep.join(result)
  509. # end output
  510. __str__ = output
  511. def __repr__(self):
  512. L = []
  513. items = self.items()
  514. items.sort()
  515. for K,V in items:
  516. L.append( '%s=%s' % (K,repr(V.value) ) )
  517. return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))
  518. def js_output(self, attrs=None):
  519. """Return a string suitable for JavaScript."""
  520. result = []
  521. items = self.items()
  522. items.sort()
  523. for K,V in items:
  524. result.append( V.js_output(attrs) )
  525. return _nulljoin(result)
  526. # end js_output
  527. def load(self, rawdata):
  528. """Load cookies from a string (presumably HTTP_COOKIE) or
  529. from a dictionary. Loading cookies from a dictionary 'd'
  530. is equivalent to calling:
  531. map(Cookie.__setitem__, d.keys(), d.values())
  532. """
  533. if type(rawdata) == type(""):
  534. self.__ParseString(rawdata)
  535. else:
  536. # self.update() wouldn't call our custom __setitem__
  537. for k, v in rawdata.items():
  538. self[k] = v
  539. return
  540. # end load()
  541. def __ParseString(self, str, patt=_CookiePattern):
  542. i = 0 # Our starting point
  543. n = len(str) # Length of string
  544. M = None # current morsel
  545. while 0 <= i < n:
  546. # Start looking for a cookie
  547. match = patt.search(str, i)
  548. if not match: break # No more cookies
  549. K,V = match.group("key"), match.group("val")
  550. i = match.end(0)
  551. # Parse the key, value in case it's metainfo
  552. if K[0] == "$":
  553. # We ignore attributes which pertain to the cookie
  554. # mechanism as a whole. See RFC 2109.
  555. # (Does anyone care?)
  556. if M:
  557. M[ K[1:] ] = V
  558. elif K.lower() in Morsel._reserved:
  559. if M:
  560. M[ K ] = _unquote(V)
  561. else:
  562. rval, cval = self.value_decode(V)
  563. self.__set(K, rval, cval)
  564. M = self[K]
  565. # end __ParseString
  566. # end BaseCookie class
  567. class SimpleCookie(BaseCookie):
  568. """SimpleCookie
  569. SimpleCookie supports strings as cookie values. When setting
  570. the value using the dictionary assignment notation, SimpleCookie
  571. calls the builtin str() to convert the value to a string. Values
  572. received from HTTP are kept as strings.
  573. """
  574. def value_decode(self, val):
  575. return _unquote( val ), val
  576. def value_encode(self, val):
  577. strval = str(val)
  578. return strval, _quote( strval )
  579. # end SimpleCookie
  580. class SerialCookie(BaseCookie):
  581. """SerialCookie
  582. SerialCookie supports arbitrary objects as cookie values. All
  583. values are serialized (using cPickle) before being sent to the
  584. client. All incoming values are assumed to be valid Pickle
  585. representations. IF AN INCOMING VALUE IS NOT IN A VALID PICKLE
  586. FORMAT, THEN AN EXCEPTION WILL BE RAISED.
  587. Note: Large cookie values add overhead because they must be
  588. retransmitted on every HTTP transaction.
  589. Note: HTTP has a 2k limit on the size of a cookie. This class
  590. does not check for this limit, so be careful!!!
  591. """
  592. def __init__(self, input=None):
  593. warnings.warn("SerialCookie class is insecure; do not use it",
  594. DeprecationWarning)
  595. BaseCookie.__init__(self, input)
  596. # end __init__
  597. def value_decode(self, val):
  598. # This could raise an exception!
  599. return loads( _unquote(val) ), val
  600. def value_encode(self, val):
  601. return val, _quote( dumps(val) )
  602. # end SerialCookie
  603. class SmartCookie(BaseCookie):
  604. """SmartCookie
  605. SmartCookie supports arbitrary objects as cookie values. If the
  606. object is a string, then it is quoted. If the object is not a
  607. string, however, then SmartCookie will use cPickle to serialize
  608. the object into a string representation.
  609. Note: Large cookie values add overhead because they must be
  610. retransmitted on every HTTP transaction.
  611. Note: HTTP has a 2k limit on the size of a cookie. This class
  612. does not check for this limit, so be careful!!!
  613. """
  614. def __init__(self, input=None):
  615. warnings.warn("Cookie/SmartCookie class is insecure; do not use it",
  616. DeprecationWarning)
  617. BaseCookie.__init__(self, input)
  618. # end __init__
  619. def value_decode(self, val):
  620. strval = _unquote(val)
  621. try:
  622. return loads(strval), val
  623. except:
  624. return strval, val
  625. def value_encode(self, val):
  626. if type(val) == type(""):
  627. return val, _quote(val)
  628. else:
  629. return val, _quote( dumps(val) )
  630. # end SmartCookie
  631. ###########################################################
  632. # Backwards Compatibility: Don't break any existing code!
  633. # We provide Cookie() as an alias for SmartCookie()
  634. Cookie = SmartCookie
  635. #
  636. ###########################################################
  637. def _test():
  638. import doctest, Cookie
  639. return doctest.testmod(Cookie)
  640. if __name__ == "__main__":
  641. _test()
  642. #Local Variables:
  643. #tab-width: 4
  644. #end: