Cookie.py 26 KB

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