home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 May / maximum-cd-2009-05.iso / DiscContents / XBMC_for_Windows-8.10.exe / system / python / spyce / Cookie.py < prev    next >
Encoding:
Python Source  |  2008-11-03  |  25.7 KB  |  748 lines

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