Skip to content
Myr

oreos!

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 5a7fbbb · Browse files · 4 files+1197 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+1197 added−0 removed

  • other:+1197 added−0 removed

4 files+1197 added−0 removed

added:requests/packages/oreos/__init__.py+3 added
1# -*- coding: utf-8 -*-23from .core import *
added:requests/packages/oreos/core.py+25 added
1# -*- coding: utf-8 -*-23"""4oreos.core5~~~~~~~~~~67The creamy white center.8"""910from .structures import MultiDict11from .monkeys import SimpleCookie121314def dict_from_string(s):15 """Returns a MultiDict with Cookies."""1617 cookies = MultiDict()1819 c = SimpleCookie()20 c.load(s)2122 for k,v in c.items():23 cookies.add(k, v.value)2425 return cookies
added:requests/packages/oreos/monkeys.py+770 added
1# -*- coding: utf-8 -*-23"""4oreos.monkeys5~~~~~~~~~~~~~67Monkeypatches.8"""9#!/usr/bin/env python10#1112####13# Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>14#15# All Rights Reserved16#17# Permission to use, copy, modify, and distribute this software18# and its documentation for any purpose and without fee is hereby19# granted, provided that the above copyright notice appear in all20# copies and that both that copyright notice and this permission21# notice appear in supporting documentation, and that the name of22# Timothy O'Malley not be used in advertising or publicity23# pertaining to distribution of the software without specific, written24# prior permission.25#26# Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS27# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY28# AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR29# ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES30# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,31# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS32# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR33# PERFORMANCE OF THIS SOFTWARE.34#35####36#37# Id: Cookie.py,v 2.29 2000/08/23 05:28:49 timo Exp38# by Timothy O'Malley <timo@alum.mit.edu>39#40# Cookie.py is a Python module for the handling of HTTP41# cookies as a Python dictionary. See RFC 2109 for more42# information on cookies.43#44# The original idea to treat Cookies as a dictionary came from45# Dave Mitchell (davem@magnet.com) in 1995, when he released the46# first version of nscookie.py.47#48####4950r"""51Here's a sample session to show how to use this module.52At the moment, this is the only documentation.5354The Basics55----------5657Importing is easy..5859 >>> import Cookie6061Most of the time you start by creating a cookie. Cookies come in62three flavors, each with slightly different encoding semantics, but63more on that later.6465 >>> C = Cookie.SimpleCookie()66 >>> C = Cookie.SerialCookie()67 >>> C = Cookie.SmartCookie()6869[Note: Long-time users of Cookie.py will remember using70Cookie.Cookie() to create an Cookie object. Although deprecated, it71is still supported by the code. See the Backward Compatibility notes72for more information.]7374Once you've created your Cookie, you can add values just as if it were75a dictionary.7677 >>> C = Cookie.SmartCookie()78 >>> C["fig"] = "newton"79 >>> C["sugar"] = "wafer"80 >>> C.output()81 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'8283Notice that the printable representation of a Cookie is the84appropriate format for a Set-Cookie: header. This is the85default behavior. You can change the header and printed86attributes by using the .output() function8788 >>> C = Cookie.SmartCookie()89 >>> C["rocky"] = "road"90 >>> C["rocky"]["path"] = "/cookie"91 >>> print C.output(header="Cookie:")92 Cookie: rocky=road; Path=/cookie93 >>> print C.output(attrs=[], header="Cookie:")94 Cookie: rocky=road9596The load() method of a Cookie extracts cookies from a string. In a97CGI script, you would use this method to extract the cookies from the98HTTP_COOKIE environment variable.99100 >>> C = Cookie.SmartCookie()101 >>> C.load("chips=ahoy; vienna=finger")102 >>> C.output()103 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'104105The load() method is darn-tootin smart about identifying cookies106within a string. Escaped quotation marks, nested semicolons, and other107such trickeries do not confuse it.108109 >>> C = Cookie.SmartCookie()110 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')111 >>> print C112 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"113114Each element of the Cookie also supports all of the RFC 2109115Cookie attributes. Here's an example which sets the Path116attribute.117118 >>> C = Cookie.SmartCookie()119 >>> C["oreo"] = "doublestuff"120 >>> C["oreo"]["path"] = "/"121 >>> print C122 Set-Cookie: oreo=doublestuff; Path=/123124Each dictionary element has a 'value' attribute, which gives you125back the value associated with the key.126127 >>> C = Cookie.SmartCookie()128 >>> C["twix"] = "none for you"129 >>> C["twix"].value130 'none for you'131132133A Bit More Advanced134-------------------135136As mentioned before, there are three different flavors of Cookie137objects, each with different encoding/decoding semantics. This138section briefly discusses the differences.139140SimpleCookie141142The SimpleCookie expects that all values should be standard strings.143Just to be sure, SimpleCookie invokes the str() builtin to convert144the value to a string, when the values are set dictionary-style.145146 >>> C = Cookie.SimpleCookie()147 >>> C["number"] = 7148 >>> C["string"] = "seven"149 >>> C["number"].value150 '7'151 >>> C["string"].value152 'seven'153 >>> C.output()154 'Set-Cookie: number=7\r\nSet-Cookie: string=seven'155156157SerialCookie158159The SerialCookie expects that all values should be serialized using160cPickle (or pickle, if cPickle isn't available). As a result of161serializing, SerialCookie can save almost any Python object to a162value, and recover the exact same object when the cookie has been163returned. (SerialCookie can yield some strange-looking cookie164values, however.)165166 >>> C = Cookie.SerialCookie()167 >>> C["number"] = 7168 >>> C["string"] = "seven"169 >>> C["number"].value170 7171 >>> C["string"].value172 'seven'173 >>> C.output()174 'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string="S\'seven\'\\012p1\\012."'175176Be warned, however, if SerialCookie cannot de-serialize a value (because177it isn't a valid pickle'd object), IT WILL RAISE AN EXCEPTION.178179180SmartCookie181182The SmartCookie combines aspects of each of the other two flavors.183When setting a value in a dictionary-fashion, the SmartCookie will184serialize (ala cPickle) the value *if and only if* it isn't a185Python string. String objects are *not* serialized. Similarly,186when the load() method parses out values, it attempts to de-serialize187the value. If it fails, then it fallsback to treating the value188as a string.189190 >>> C = Cookie.SmartCookie()191 >>> C["number"] = 7192 >>> C["string"] = "seven"193 >>> C["number"].value194 7195 >>> C["string"].value196 'seven'197 >>> C.output()198 'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string=seven'199200201Backwards Compatibility202-----------------------203204In order to keep compatibilty with earlier versions of Cookie.py,205it is still possible to use Cookie.Cookie() to create a Cookie. In206fact, this simply returns a SmartCookie.207208 >>> C = Cookie.Cookie()209 >>> print C.__class__.__name__210 SmartCookie211212213Finis.214""" #"215# ^216# |----helps out font-lock217218#219# Import our required modules220#221import string222223try:224 from cPickle import dumps, loads225except ImportError:226 from pickle import dumps, loads227228import re, warnings229230__all__ = ["CookieError","BaseCookie","SimpleCookie","SerialCookie",231 "SmartCookie","Cookie"]232233_nulljoin = ''.join234_semispacejoin = '; '.join235_spacejoin = ' '.join236237#238# Define an exception visible to External modules239#240class CookieError(Exception):241 pass242243244# These quoting routines conform to the RFC2109 specification, which in245# turn references the character definitions from RFC2068. They provide246# a two-way quoting algorithm. Any non-text character is translated247# into a 4 character sequence: a forward-slash followed by the248# three-digit octal equivalent of the character. Any '\' or '"' is249# quoted with a preceeding '\' slash.250#251# These are taken from RFC2068 and RFC2109.252# _LegalChars is the list of chars which don't require "'s253# _Translator hash-table for fast quoting254#255_LegalChars = string.ascii_letters + string.digits + "!#$%&'*+-.^_`|~[]_"256_Translator = {257 '\000' : '\\000', '\001' : '\\001', '\002' : '\\002',258 '\003' : '\\003', '\004' : '\\004', '\005' : '\\005',259 '\006' : '\\006', '\007' : '\\007', '\010' : '\\010',260 '\011' : '\\011', '\012' : '\\012', '\013' : '\\013',261 '\014' : '\\014', '\015' : '\\015', '\016' : '\\016',262 '\017' : '\\017', '\020' : '\\020', '\021' : '\\021',263 '\022' : '\\022', '\023' : '\\023', '\024' : '\\024',264 '\025' : '\\025', '\026' : '\\026', '\027' : '\\027',265 '\030' : '\\030', '\031' : '\\031', '\032' : '\\032',266 '\033' : '\\033', '\034' : '\\034', '\035' : '\\035',267 '\036' : '\\036', '\037' : '\\037',268269 # Because of the way browsers really handle cookies (as opposed270 # to what the RFC says) we also encode , and ;271272 ',' : '\\054', ';' : '\\073',273274 '"' : '\\"', '\\' : '\\\\',275276 '\177' : '\\177', '\200' : '\\200', '\201' : '\\201',277 '\202' : '\\202', '\203' : '\\203', '\204' : '\\204',278 '\205' : '\\205', '\206' : '\\206', '\207' : '\\207',279 '\210' : '\\210', '\211' : '\\211', '\212' : '\\212',280 '\213' : '\\213', '\214' : '\\214', '\215' : '\\215',281 '\216' : '\\216', '\217' : '\\217', '\220' : '\\220',282 '\221' : '\\221', '\222' : '\\222', '\223' : '\\223',283 '\224' : '\\224', '\225' : '\\225', '\226' : '\\226',284 '\227' : '\\227', '\230' : '\\230', '\231' : '\\231',285 '\232' : '\\232', '\233' : '\\233', '\234' : '\\234',286 '\235' : '\\235', '\236' : '\\236', '\237' : '\\237',287 '\240' : '\\240', '\241' : '\\241', '\242' : '\\242',288 '\243' : '\\243', '\244' : '\\244', '\245' : '\\245',289 '\246' : '\\246', '\247' : '\\247', '\250' : '\\250',290 '\251' : '\\251', '\252' : '\\252', '\253' : '\\253',291 '\254' : '\\254', '\255' : '\\255', '\256' : '\\256',292 '\257' : '\\257', '\260' : '\\260', '\261' : '\\261',293 '\262' : '\\262', '\263' : '\\263', '\264' : '\\264',294 '\265' : '\\265', '\266' : '\\266', '\267' : '\\267',295 '\270' : '\\270', '\271' : '\\271', '\272' : '\\272',296 '\273' : '\\273', '\274' : '\\274', '\275' : '\\275',297 '\276' : '\\276', '\277' : '\\277', '\300' : '\\300',298 '\301' : '\\301', '\302' : '\\302', '\303' : '\\303',299 '\304' : '\\304', '\305' : '\\305', '\306' : '\\306',300 '\307' : '\\307', '\310' : '\\310', '\311' : '\\311',301 '\312' : '\\312', '\313' : '\\313', '\314' : '\\314',302 '\315' : '\\315', '\316' : '\\316', '\317' : '\\317',303 '\320' : '\\320', '\321' : '\\321', '\322' : '\\322',304 '\323' : '\\323', '\324' : '\\324', '\325' : '\\325',305 '\326' : '\\326', '\327' : '\\327', '\330' : '\\330',306 '\331' : '\\331', '\332' : '\\332', '\333' : '\\333',307 '\334' : '\\334', '\335' : '\\335', '\336' : '\\336',308 '\337' : '\\337', '\340' : '\\340', '\341' : '\\341',309 '\342' : '\\342', '\343' : '\\343', '\344' : '\\344',310 '\345' : '\\345', '\346' : '\\346', '\347' : '\\347',311 '\350' : '\\350', '\351' : '\\351', '\352' : '\\352',312 '\353' : '\\353', '\354' : '\\354', '\355' : '\\355',313 '\356' : '\\356', '\357' : '\\357', '\360' : '\\360',314 '\361' : '\\361', '\362' : '\\362', '\363' : '\\363',315 '\364' : '\\364', '\365' : '\\365', '\366' : '\\366',316 '\367' : '\\367', '\370' : '\\370', '\371' : '\\371',317 '\372' : '\\372', '\373' : '\\373', '\374' : '\\374',318 '\375' : '\\375', '\376' : '\\376', '\377' : '\\377'319 }320321_idmap = ''.join(chr(x) for x in xrange(256))322323def _quote(str, LegalChars=_LegalChars,324 idmap=_idmap, translate=string.translate):325 #326 # If the string does not need to be double-quoted,327 # then just return the string. Otherwise, surround328 # the string in doublequotes and precede quote (with a \)329 # special characters.330 #331 if "" == translate(str, idmap, LegalChars):332 return str333 else:334 return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'335# end _quote336337338_OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")339_QuotePatt = re.compile(r"[\\].")340341def _unquote(str):342 # If there aren't any doublequotes,343 # then there can't be any special characters. See RFC 2109.344 if len(str) < 2:345 return str346 if str[0] != '"' or str[-1] != '"':347 return str348349 # We have to assume that we must decode this string.350 # Down to work.351352 # Remove the "s353 str = str[1:-1]354355 # Check for special sequences. Examples:356 # \012 --> \n357 # \" --> "358 #359 i = 0360 n = len(str)361 res = []362 while 0 <= i < n:363 Omatch = _OctalPatt.search(str, i)364 Qmatch = _QuotePatt.search(str, i)365 if not Omatch and not Qmatch: # Neither matched366 res.append(str[i:])367 break368 # else:369 j = k = -1370 if Omatch: j = Omatch.start(0)371 if Qmatch: k = Qmatch.start(0)372 if Qmatch and ( not Omatch or k < j ): # QuotePatt matched373 res.append(str[i:k])374 res.append(str[k+1])375 i = k+2376 else: # OctalPatt matched377 res.append(str[i:j])378 res.append( chr( int(str[j+1:j+4], 8) ) )379 i = j+4380 return _nulljoin(res)381# end _unquote382383# The _getdate() routine is used to set the expiration time in384# the cookie's HTTP header. By default, _getdate() returns the385# current time in the appropriate "expires" format for a386# Set-Cookie header. The one optional argument is an offset from387# now, in seconds. For example, an offset of -3600 means "one hour ago".388# The offset may be a floating point number.389#390391_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']392393_monthname = [None,394 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',395 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']396397def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):398 from time import gmtime, time399 now = time()400 year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)401 return "%s, %02d-%3s-%4d %02d:%02d:%02d GMT" % \402 (weekdayname[wd], day, monthname[month], year, hh, mm, ss)403404405#406# A class to hold ONE key,value pair.407# In a cookie, each such pair may have several attributes.408# so this class is used to keep the attributes associated409# with the appropriate key,value pair.410# This class also includes a coded_value attribute, which411# is used to hold the network representation of the412# value. This is most useful when Python objects are413# pickled for network transit.414#415416class Morsel(dict):417 # RFC 2109 lists these attributes as reserved:418 # path comment domain419 # max-age secure version420 #421 # For historical reasons, these attributes are also reserved:422 # expires423 #424 # This is an extension from Microsoft:425 # httponly426 #427 # This dictionary provides a mapping from the lowercase428 # variant on the left to the appropriate traditional429 # 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 "httponly" : "httponly",437 "version" : "Version",438 }439440 def __init__(self):441 # Set defaults442 self.key = self.value = self.coded_value = None443444 # Set default attributes445 for K in self._reserved:446 dict.__setitem__(self, K, "")447 # end __init__448449 def __setitem__(self, K, V):450 K = K.lower()451 if not K in self._reserved:452 raise CookieError("Invalid Attribute %s" % K)453 dict.__setitem__(self, K, V)454 # end __setitem__455456 def isReservedKey(self, K):457 return K.lower() in self._reserved458 # end isReservedKey459460 def set(self, key, val, coded_val,461 LegalChars=_LegalChars,462 idmap=_idmap, translate=string.translate):463 # First we verify that the key isn't a reserved word464 # Second we make sure it only contains legal characters465 if key.lower() in self._reserved:466 raise CookieError("Attempt to set a reserved key: %s" % key)467 if "" != translate(key, idmap, LegalChars):468 raise CookieError("Illegal key value: %s" % key)469470 # It's a good key, so save it.471 self.key = key472 self.value = val473 self.coded_value = coded_val474 # end set475476 def output(self, attrs=None, header = "Set-Cookie:"):477 return "%s %s" % ( header, self.OutputString(attrs) )478479 __str__ = output480481 def __repr__(self):482 return '<%s: %s=%s>' % (self.__class__.__name__,483 self.key, repr(self.value) )484485 def js_output(self, attrs=None):486 # Print javascript487 return """488 <script type="text/javascript">489 <!-- begin hiding490 document.cookie = \"%s\";491 // end hiding -->492 </script>493 """ % ( self.OutputString(attrs).replace('"',r'\"'), )494 # end js_output()495496 def OutputString(self, attrs=None):497 # Build up our result498 #499 result = []500 RA = result.append501502 # First, the key=value pair503 RA("%s=%s" % (self.key, self.coded_value))504505 # Now add any defined attributes506 if attrs is None:507 attrs = self._reserved508 items = self.items()509 items.sort()510 for K,V in items:511 if V == "": continue512 if K not in attrs: continue513 if K == "expires" and type(V) == type(1):514 RA("%s=%s" % (self._reserved[K], _getdate(V)))515 elif K == "max-age" and type(V) == type(1):516 RA("%s=%d" % (self._reserved[K], V))517 elif K == "secure":518 RA(str(self._reserved[K]))519 elif K == "httponly":520 RA(str(self._reserved[K]))521 else:522 RA("%s=%s" % (self._reserved[K], V))523524 # Return the result525 return _semispacejoin(result)526 # end OutputString527# end Morsel class528529530531#532# Pattern for finding cookie533#534# This used to be strict parsing based on the RFC2109 and RFC2068535# specifications. I have since discovered that MSIE 3.0x doesn't536# follow the character rules outlined in those specs. As a537# result, the parsing rules here are less strict.538#539540_LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=\[\]\_]"541542_CookiePattern = re.compile(543 r"(?x)" # This is a Verbose pattern544 r"(?P<key>" # Start of group 'key'545 ""+ _LegalCharsPatt +"+?" # Any word of at least one letter, nongreedy546 r")" # End of group 'key'547 r"\s*=\s*" # Equal Sign548 r"(?P<val>" # Start of group 'val'549 r'"(?:[^\\"]|\\.)*"' # Any doublequoted string550 r"|" # or551 r"\w{3},\s[\w\d-]{9,11}\s[\d:]{8}\sGMT" # Special case for "expires" attr552 r"|" # or553 ""+ _LegalCharsPatt +"*" # Any word or empty string554 r")" # End of group 'val'555 r"\s*;?" # Probably ending in a semi-colon556 )557558559# At long last, here is the cookie class.560# Using this class is almost just like using a dictionary.561# See this module's docstring for example usage.562#563class BaseCookie(dict):564 # A container class for a set of Morsels565 #566567 def value_decode(self, val):568 """real_value, coded_value = value_decode(STRING)569 Called prior to setting a cookie's value from the network570 representation. The VALUE is the value read from HTTP571 header.572 Override this function to modify the behavior of cookies.573 """574 return val, val575 # end value_encode576577 def value_encode(self, val):578 """real_value, coded_value = value_encode(VALUE)579 Called prior to setting a cookie's value from the dictionary580 representation. The VALUE is the value being assigned.581 Override this function to modify the behavior of cookies.582 """583 strval = str(val)584 return strval, strval585 # end value_encode586587 def __init__(self, input=None):588 if input: self.load(input)589 # end __init__590591 def __set(self, key, real_value, coded_value):592 """Private method for setting a cookie's value"""593 M = self.get(key, Morsel())594 M.set(key, real_value, coded_value)595 dict.__setitem__(self, key, M)596 # end __set597598 def __setitem__(self, key, value):599 """Dictionary style assignment."""600 rval, cval = self.value_encode(value)601 self.__set(key, rval, cval)602 # end __setitem__603604 def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):605 """Return a string suitable for HTTP."""606 result = []607 items = self.items()608 items.sort()609 for K,V in items:610 result.append( V.output(attrs, header) )611 return sep.join(result)612 # end output613614 __str__ = output615616 def __repr__(self):617 L = []618 items = self.items()619 items.sort()620 for K,V in items:621 L.append( '%s=%s' % (K,repr(V.value) ) )622 return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))623624 def js_output(self, attrs=None):625 """Return a string suitable for JavaScript."""626 result = []627 items = self.items()628 items.sort()629 for K,V in items:630 result.append( V.js_output(attrs) )631 return _nulljoin(result)632 # end js_output633634 def load(self, rawdata):635 """Load cookies from a string (presumably HTTP_COOKIE) or636 from a dictionary. Loading cookies from a dictionary 'd'637 is equivalent to calling:638 map(Cookie.__setitem__, d.keys(), d.values())639 """640 if type(rawdata) == type(""):641 self.__ParseString(rawdata)642 else:643 # self.update() wouldn't call our custom __setitem__644 for k, v in rawdata.items():645 self[k] = v646 return647 # end load()648649 def __ParseString(self, str, patt=_CookiePattern):650 i = 0 # Our starting point651 n = len(str) # Length of string652 M = None # current morsel653654 while 0 <= i < n:655 # Start looking for a cookie656 match = patt.search(str, i)657 if not match: break # No more cookies658659 K,V = match.group("key"), match.group("val")660 i = match.end(0)661662 # Parse the key, value in case it's metainfo663 if K[0] == "$":664 # We ignore attributes which pertain to the cookie665 # mechanism as a whole. See RFC 2109.666 # (Does anyone care?)667 if M:668 M[ K[1:] ] = V669 elif K.lower() in Morsel._reserved:670 if M:671 M[ K ] = _unquote(V)672 else:673 rval, cval = self.value_decode(V)674 self.__set(K, rval, cval)675 M = self[K]676 # end __ParseString677# end BaseCookie class678679class SimpleCookie(BaseCookie):680 """SimpleCookie681 SimpleCookie supports strings as cookie values. When setting682 the value using the dictionary assignment notation, SimpleCookie683 calls the builtin str() to convert the value to a string. Values684 received from HTTP are kept as strings.685 """686 def value_decode(self, val):687 return _unquote( val ), val688 def value_encode(self, val):689 strval = str(val)690 return strval, _quote( strval )691# end SimpleCookie692693class SerialCookie(BaseCookie):694 """SerialCookie695 SerialCookie supports arbitrary objects as cookie values. All696 values are serialized (using cPickle) before being sent to the697 client. All incoming values are assumed to be valid Pickle698 representations. IF AN INCOMING VALUE IS NOT IN A VALID PICKLE699 FORMAT, THEN AN EXCEPTION WILL BE RAISED.700701 Note: Large cookie values add overhead because they must be702 retransmitted on every HTTP transaction.703704 Note: HTTP has a 2k limit on the size of a cookie. This class705 does not check for this limit, so be careful!!!706 """707 def __init__(self, input=None):708 warnings.warn("SerialCookie class is insecure; do not use it",709 DeprecationWarning)710 BaseCookie.__init__(self, input)711 # end __init__712 def value_decode(self, val):713 # This could raise an exception!714 return loads( _unquote(val) ), val715 def value_encode(self, val):716 return val, _quote( dumps(val) )717# end SerialCookie718719class SmartCookie(BaseCookie):720 """SmartCookie721 SmartCookie supports arbitrary objects as cookie values. If the722 object is a string, then it is quoted. If the object is not a723 string, however, then SmartCookie will use cPickle to serialize724 the object into a string representation.725726 Note: Large cookie values add overhead because they must be727 retransmitted on every HTTP transaction.728729 Note: HTTP has a 2k limit on the size of a cookie. This class730 does not check for this limit, so be careful!!!731 """732 def __init__(self, input=None):733 warnings.warn("Cookie/SmartCookie class is insecure; do not use it",734 DeprecationWarning)735 BaseCookie.__init__(self, input)736 # end __init__737 def value_decode(self, val):738 strval = _unquote(val)739 try:740 return loads(strval), val741 except:742 return strval, val743 def value_encode(self, val):744 if type(val) == type(""):745 return val, _quote(val)746 else:747 return val, _quote( dumps(val) )748# end SmartCookie749750751###########################################################752# Backwards Compatibility: Don't break any existing code!753754# We provide Cookie() as an alias for SmartCookie()755Cookie = SmartCookie756757#758###########################################################759760def _test():761 import doctest, Cookie762 return doctest.testmod(Cookie)763764if __name__ == "__main__":765 _test()766767768#Local Variables:769#tab-width: 4770#end:
added:requests/packages/oreos/structures.py+399 added
1# -*- coding: utf-8 -*-23"""4oreos.sructures5~~~~~~~~~~~~~~~67The plastic blue packaging.89This is mostly directly stolen from mitsuhiko/werkzeug.10"""1112__all__ = ('MultiDict',)1314class _Missing(object):1516 def __repr__(self):17 return 'no value'1819 def __reduce__(self):20 return '_missing'2122_missing = _Missing()23242526def iter_multi_items(mapping):27 """Iterates over the items of a mapping yielding keys and values28 without dropping any from more complex structures.29 """30 if isinstance(mapping, MultiDict):31 for item in mapping.iteritems(multi=True):32 yield item33 elif isinstance(mapping, dict):34 for key, value in mapping.iteritems():35 if isinstance(value, (tuple, list)):36 for value in value:37 yield key, value38 else:39 yield key, value40 else:41 for item in mapping:42 yield item43444546class TypeConversionDict(dict):47 """Works like a regular dict but the :meth:`get` method can perform48 type conversions. :class:`MultiDict` and :class:`CombinedMultiDict`49 are subclasses of this class and provide the same feature.5051 .. versionadded:: 0.552 """5354 def get(self, key, default=None, type=None):55 """Return the default value if the requested data doesn't exist.56 If `type` is provided and is a callable it should convert the value,57 return it or raise a :exc:`ValueError` if that is not possible. In58 this case the function will return the default as if the value was not59 found:6061 >>> d = TypeConversionDict(foo='42', bar='blub')62 >>> d.get('foo', type=int)63 4264 >>> d.get('bar', -1, type=int)65 -16667 :param key: The key to be looked up.68 :param default: The default value to be returned if the key can't69 be looked up. If not further specified `None` is70 returned.71 :param type: A callable that is used to cast the value in the72 :class:`MultiDict`. If a :exc:`ValueError` is raised73 by this callable the default value is returned.74 """75 try:76 rv = self[key]77 if type is not None:78 rv = type(rv)79 except (KeyError, ValueError):80 rv = default81 return rv828384class MultiDict(TypeConversionDict):85 """A :class:`MultiDict` is a dictionary subclass customized to deal with86 multiple values for the same key which is for example used by the parsing87 functions in the wrappers. This is necessary because some HTML form88 elements pass multiple values for the same key.8990 :class:`MultiDict` implements all standard dictionary methods.91 Internally, it saves all values for a key as a list, but the standard dict92 access methods will only return the first value for a key. If you want to93 gain access to the other values, too, you have to use the `list` methods as94 explained below.9596 Basic Usage:9798 >>> d = MultiDict([('a', 'b'), ('a', 'c')])99 >>> d100 MultiDict([('a', 'b'), ('a', 'c')])101 >>> d['a']102 'b'103 >>> d.getlist('a')104 ['b', 'c']105 >>> 'a' in d106 True107108 It behaves like a normal dict thus all dict functions will only return the109 first value when multiple values for one key are found.110111 From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a112 subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will113 render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP114 exceptions.115116 A :class:`MultiDict` can be constructed from an iterable of117 ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2118 onwards some keyword parameters.119120 :param mapping: the initial value for the :class:`MultiDict`. Either a121 regular dict, an iterable of ``(key, value)`` tuples122 or `None`.123 """124125 def __init__(self, mapping=None):126 if isinstance(mapping, MultiDict):127 dict.__init__(self, ((k, l[:]) for k, l in mapping.iterlists()))128 elif isinstance(mapping, dict):129 tmp = {}130 for key, value in mapping.iteritems():131 if isinstance(value, (tuple, list)):132 value = list(value)133 else:134 value = [value]135 tmp[key] = value136 dict.__init__(self, tmp)137 else:138 tmp = {}139 for key, value in mapping or ():140 tmp.setdefault(key, []).append(value)141 dict.__init__(self, tmp)142143 def __getstate__(self):144 return dict(self.lists())145146 def __setstate__(self, value):147 dict.clear(self)148 dict.update(self, value)149150 def __iter__(self):151 return self.iterkeys()152153 def __getitem__(self, key):154 """Return the first data value for this key;155 raises KeyError if not found.156157 :param key: The key to be looked up.158 :raise KeyError: if the key does not exist.159 """160 if key in self:161 return dict.__getitem__(self, key)[0]162 raise KeyError(key)163164 def __setitem__(self, key, value):165 """Like :meth:`add` but removes an existing key first.166167 :param key: the key for the value.168 :param value: the value to set.169 """170 dict.__setitem__(self, key, [value])171172 def add(self, key, value):173 """Adds a new value for the key.174175 .. versionadded:: 0.6176177 :param key: the key for the value.178 :param value: the value to add.179 """180 dict.setdefault(self, key, []).append(value)181182 def getlist(self, key, type=None):183 """Return the list of items for a given key. If that key is not in the184 `MultiDict`, the return value will be an empty list. Just as `get`185 `getlist` accepts a `type` parameter. All items will be converted186 with the callable defined there.187188 :param key: The key to be looked up.189 :param type: A callable that is used to cast the value in the190 :class:`MultiDict`. If a :exc:`ValueError` is raised191 by this callable the value will be removed from the list.192 :return: a :class:`list` of all the values for the key.193 """194 try:195 rv = dict.__getitem__(self, key)196 except KeyError:197 return []198 if type is None:199 return list(rv)200 result = []201 for item in rv:202 try:203 result.append(type(item))204 except ValueError:205 pass206 return result207208 def setlist(self, key, new_list):209 """Remove the old values for a key and add new ones. Note that the list210 you pass the values in will be shallow-copied before it is inserted in211 the dictionary.212213 >>> d = MultiDict()214 >>> d.setlist('foo', ['1', '2'])215 >>> d['foo']216 '1'217 >>> d.getlist('foo')218 ['1', '2']219220 :param key: The key for which the values are set.221 :param new_list: An iterable with the new values for the key. Old values222 are removed first.223 """224 dict.__setitem__(self, key, list(new_list))225226 def setdefault(self, key, default=None):227 """Returns the value for the key if it is in the dict, otherwise it228 returns `default` and sets that value for `key`.229230 :param key: The key to be looked up.231 :param default: The default value to be returned if the key is not232 in the dict. If not further specified it's `None`.233 """234 if key not in self:235 self[key] = default236 else:237 default = self[key]238 return default239240 def setlistdefault(self, key, default_list=None):241 """Like `setdefault` but sets multiple values. The list returned242 is not a copy, but the list that is actually used internally. This243 means that you can put new values into the dict by appending items244 to the list:245246 >>> d = MultiDict({"foo": 1})247 >>> d.setlistdefault("foo").extend([2, 3])248 >>> d.getlist("foo")249 [1, 2, 3]250251 :param key: The key to be looked up.252 :param default: An iterable of default values. It is either copied253 (in case it was a list) or converted into a list254 before returned.255 :return: a :class:`list`256 """257 if key not in self:258 default_list = list(default_list or ())259 dict.__setitem__(self, key, default_list)260 else:261 default_list = dict.__getitem__(self, key)262 return default_list263264 def items(self, multi=False):265 """Return a list of ``(key, value)`` pairs.266267 :param multi: If set to `True` the list returned will have a268 pair for each value of each key. Otherwise it269 will only contain pairs for the first value of270 each key.271272 :return: a :class:`list`273 """274 return list(self.iteritems(multi))275276 def lists(self):277 """Return a list of ``(key, values)`` pairs, where values is the list of278 all values associated with the key.279280 :return: a :class:`list`281 """282 return list(self.iterlists())283284 def values(self):285 """Returns a list of the first value on every key's value list.286287 :return: a :class:`list`.288 """289 return [self[key] for key in self.iterkeys()]290291 def listvalues(self):292 """Return a list of all values associated with a key. Zipping293 :meth:`keys` and this is the same as calling :meth:`lists`:294295 >>> d = MultiDict({"foo": [1, 2, 3]})296 >>> zip(d.keys(), d.listvalues()) == d.lists()297 True298299 :return: a :class:`list`300 """301 return list(self.iterlistvalues())302303 def iteritems(self, multi=False):304 """Like :meth:`items` but returns an iterator."""305 for key, values in dict.iteritems(self):306 if multi:307 for value in values:308 yield key, value309 else:310 yield key, values[0]311312 def iterlists(self):313 """Like :meth:`items` but returns an iterator."""314 for key, values in dict.iteritems(self):315 yield key, list(values)316317 def itervalues(self):318 """Like :meth:`values` but returns an iterator."""319 for values in dict.itervalues(self):320 yield values[0]321322 def iterlistvalues(self):323 """Like :meth:`listvalues` but returns an iterator."""324 return dict.itervalues(self)325326 def copy(self):327 """Return a shallow copy of this object."""328 return self.__class__(self)329330 def to_dict(self, flat=True):331 """Return the contents as regular dict. If `flat` is `True` the332 returned dict will only have the first item present, if `flat` is333 `False` all values will be returned as lists.334335 :param flat: If set to `False` the dict returned will have lists336 with all the values in it. Otherwise it will only337 contain the first value for each key.338 :return: a :class:`dict`339 """340 if flat:341 return dict(self.iteritems())342 return dict(self.lists())343344 def update(self, other_dict):345 """update() extends rather than replaces existing key lists."""346 for key, value in iter_multi_items(other_dict):347 MultiDict.add(self, key, value)348349 def pop(self, key, default=_missing):350 """Pop the first item for a list on the dict. Afterwards the351 key is removed from the dict, so additional values are discarded:352353 >>> d = MultiDict({"foo": [1, 2, 3]})354 >>> d.pop("foo")355 1356 >>> "foo" in d357 False358359 :param key: the key to pop.360 :param default: if provided the value to return if the key was361 not in the dictionary.362 """363 try:364 return dict.pop(self, key)[0]365 except KeyError, e:366 if default is not _missing:367 return default368 raise KeyError(str(e))369370 def popitem(self):371 """Pop an item from the dict."""372 try:373 item = dict.popitem(self)374 return (item[0], item[1][0])375 except KeyError, e:376 raise KeyError(str(e))377378 def poplist(self, key):379 """Pop the list for a key from the dict. If the key is not in the dict380 an empty list is returned.381382 .. versionchanged:: 0.5383 If the key does no longer exist a list is returned instead of384 raising an error.385 """386 return dict.pop(self, key, [])387388 def popitemlist(self):389 """Pop a ``(key, list)`` tuple from the dict."""390 try:391 return dict.popitem(self)392 except KeyError, e:393 raise KeyError(str(e))394395 def __copy__(self):396 return self.copy()397398 def __repr__(self):399 return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))