home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / COOKIE.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  24.8 KB  |  727 lines

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