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.

Cookie.py 25KB

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