remove 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 15694fa · Browse files · 4 files·+0 added−1199 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+0 added−1199 removed
- other:+0 added−1199 removed
Provenance
- Commit
3ee5941- Tree
56f8020- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
15694fa
4 files changed+0 added−1199 removed
deleted:requests/packages/oreos/__init__.py-3 removed
1-# -*- coding: utf-8 -*-2-3-from .core import dict_from_stringdeleted:requests/packages/oreos/core.py-24 removed
1-# -*- coding: utf-8 -*-2-3-"""4-oreos.core5-~~~~~~~~~~6-7-The creamy white center.8-"""9-10-from .monkeys import SimpleCookie11-12-13-def dict_from_string(s):14- """Returns a MultiDict with Cookies."""15-16- cookies = dict()17-18- c = SimpleCookie()19- c.load(s)20-21- for k,v in c.items():22- cookies.update({k: v.value})23-24- return cookiesdeleted:requests/packages/oreos/monkeys.py-773 removed
1-# -*- coding: utf-8 -*-2-3-"""4-oreos.monkeys5-~~~~~~~~~~~~~6-7-Monkeypatches.8-"""9-#!/usr/bin/env python10-#11-12-####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-####49-50-r"""51-Here's a sample session to show how to use this module.52-At the moment, this is the only documentation.53-54-The Basics55-----------56-57-Importing is easy..58-59- >>> import Cookie60-61-Most of the time you start by creating a cookie. Cookies come in62-three flavors, each with slightly different encoding semantics, but63-more on that later.64-65- >>> C = Cookie.SimpleCookie()66- >>> C = Cookie.SerialCookie()67- >>> C = Cookie.SmartCookie()68-69-[Note: Long-time users of Cookie.py will remember using70-Cookie.Cookie() to create an Cookie object. Although deprecated, it71-is still supported by the code. See the Backward Compatibility notes72-for more information.]73-74-Once you've created your Cookie, you can add values just as if it were75-a dictionary.76-77- >>> C = Cookie.SmartCookie()78- >>> C["fig"] = "newton"79- >>> C["sugar"] = "wafer"80- >>> C.output()81- 'Set-Cookie: fig=newton\r\nSet-Cookie: sugar=wafer'82-83-Notice that the printable representation of a Cookie is the84-appropriate format for a Set-Cookie: header. This is the85-default behavior. You can change the header and printed86-attributes by using the .output() function87-88- >>> 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=road95-96-The load() method of a Cookie extracts cookies from a string. In a97-CGI script, you would use this method to extract the cookies from the98-HTTP_COOKIE environment variable.99-100- >>> C = Cookie.SmartCookie()101- >>> C.load("chips=ahoy; vienna=finger")102- >>> C.output()103- 'Set-Cookie: chips=ahoy\r\nSet-Cookie: vienna=finger'104-105-The load() method is darn-tootin smart about identifying cookies106-within a string. Escaped quotation marks, nested semicolons, and other107-such trickeries do not confuse it.108-109- >>> 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;"113-114-Each element of the Cookie also supports all of the RFC 2109115-Cookie attributes. Here's an example which sets the Path116-attribute.117-118- >>> C = Cookie.SmartCookie()119- >>> C["oreo"] = "doublestuff"120- >>> C["oreo"]["path"] = "/"121- >>> print C122- Set-Cookie: oreo=doublestuff; Path=/123-124-Each dictionary element has a 'value' attribute, which gives you125-back the value associated with the key.126-127- >>> C = Cookie.SmartCookie()128- >>> C["twix"] = "none for you"129- >>> C["twix"].value130- 'none for you'131-132-133-A Bit More Advanced134--------------------135-136-As mentioned before, there are three different flavors of Cookie137-objects, each with different encoding/decoding semantics. This138-section briefly discusses the differences.139-140-SimpleCookie141-142-The SimpleCookie expects that all values should be standard strings.143-Just to be sure, SimpleCookie invokes the str() builtin to convert144-the value to a string, when the values are set dictionary-style.145-146- >>> 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'155-156-157-SerialCookie158-159-The SerialCookie expects that all values should be serialized using160-cPickle (or pickle, if cPickle isn't available). As a result of161-serializing, SerialCookie can save almost any Python object to a162-value, and recover the exact same object when the cookie has been163-returned. (SerialCookie can yield some strange-looking cookie164-values, however.)165-166- >>> 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."'175-176-Be warned, however, if SerialCookie cannot de-serialize a value (because177-it isn't a valid pickle'd object), IT WILL RAISE AN EXCEPTION.178-179-180-SmartCookie181-182-The SmartCookie combines aspects of each of the other two flavors.183-When setting a value in a dictionary-fashion, the SmartCookie will184-serialize (ala cPickle) the value *if and only if* it isn't a185-Python string. String objects are *not* serialized. Similarly,186-when the load() method parses out values, it attempts to de-serialize187-the value. If it fails, then it fallsback to treating the value188-as a string.189-190- >>> 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'199-200-201-Backwards Compatibility202------------------------203-204-In order to keep compatibilty with earlier versions of Cookie.py,205-it is still possible to use Cookie.Cookie() to create a Cookie. In206-fact, this simply returns a SmartCookie.207-208- >>> C = Cookie.Cookie()209- >>> print C.__class__.__name__210- SmartCookie211-212-213-Finis.214-""" #"215-# ^216-# |----helps out font-lock217-218-#219-# Import our required modules220-#221-import string222-223-try:224- from cPickle import dumps, loads225-except ImportError:226- from pickle import dumps, loads227-228-import re, warnings229-230-__all__ = ["CookieError","BaseCookie","SimpleCookie","SerialCookie",231- "SmartCookie","Cookie"]232-233-_nulljoin = ''.join234-_semispacejoin = '; '.join235-_spacejoin = ' '.join236-237-#238-# Define an exception visible to External modules239-#240-class CookieError(Exception):241- pass242-243-244-# 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-# _RFC2965Forbidden is the list of forbidden chars we accept anyway253-# _LegalChars is the list of chars which don't require "'s254-# _Translator hash-table for fast quoting255-#256-_RFC2965Forbidden = "[]:{}="257-_LegalChars = ( string.ascii_letters + string.digits + 258- "!#$%&'*+-.^_`|~_@" + _RFC2965Forbidden )259-_Translator = {260- '\000' : '\\000', '\001' : '\\001', '\002' : '\\002',261- '\003' : '\\003', '\004' : '\\004', '\005' : '\\005',262- '\006' : '\\006', '\007' : '\\007', '\010' : '\\010',263- '\011' : '\\011', '\012' : '\\012', '\013' : '\\013',264- '\014' : '\\014', '\015' : '\\015', '\016' : '\\016',265- '\017' : '\\017', '\020' : '\\020', '\021' : '\\021',266- '\022' : '\\022', '\023' : '\\023', '\024' : '\\024',267- '\025' : '\\025', '\026' : '\\026', '\027' : '\\027',268- '\030' : '\\030', '\031' : '\\031', '\032' : '\\032',269- '\033' : '\\033', '\034' : '\\034', '\035' : '\\035',270- '\036' : '\\036', '\037' : '\\037',271-272- # Because of the way browsers really handle cookies (as opposed273- # to what the RFC says) we also encode , and ;274-275- ',' : '\\054', ';' : '\\073',276-277- '"' : '\\"', '\\' : '\\\\',278-279- '\177' : '\\177', '\200' : '\\200', '\201' : '\\201',280- '\202' : '\\202', '\203' : '\\203', '\204' : '\\204',281- '\205' : '\\205', '\206' : '\\206', '\207' : '\\207',282- '\210' : '\\210', '\211' : '\\211', '\212' : '\\212',283- '\213' : '\\213', '\214' : '\\214', '\215' : '\\215',284- '\216' : '\\216', '\217' : '\\217', '\220' : '\\220',285- '\221' : '\\221', '\222' : '\\222', '\223' : '\\223',286- '\224' : '\\224', '\225' : '\\225', '\226' : '\\226',287- '\227' : '\\227', '\230' : '\\230', '\231' : '\\231',288- '\232' : '\\232', '\233' : '\\233', '\234' : '\\234',289- '\235' : '\\235', '\236' : '\\236', '\237' : '\\237',290- '\240' : '\\240', '\241' : '\\241', '\242' : '\\242',291- '\243' : '\\243', '\244' : '\\244', '\245' : '\\245',292- '\246' : '\\246', '\247' : '\\247', '\250' : '\\250',293- '\251' : '\\251', '\252' : '\\252', '\253' : '\\253',294- '\254' : '\\254', '\255' : '\\255', '\256' : '\\256',295- '\257' : '\\257', '\260' : '\\260', '\261' : '\\261',296- '\262' : '\\262', '\263' : '\\263', '\264' : '\\264',297- '\265' : '\\265', '\266' : '\\266', '\267' : '\\267',298- '\270' : '\\270', '\271' : '\\271', '\272' : '\\272',299- '\273' : '\\273', '\274' : '\\274', '\275' : '\\275',300- '\276' : '\\276', '\277' : '\\277', '\300' : '\\300',301- '\301' : '\\301', '\302' : '\\302', '\303' : '\\303',302- '\304' : '\\304', '\305' : '\\305', '\306' : '\\306',303- '\307' : '\\307', '\310' : '\\310', '\311' : '\\311',304- '\312' : '\\312', '\313' : '\\313', '\314' : '\\314',305- '\315' : '\\315', '\316' : '\\316', '\317' : '\\317',306- '\320' : '\\320', '\321' : '\\321', '\322' : '\\322',307- '\323' : '\\323', '\324' : '\\324', '\325' : '\\325',308- '\326' : '\\326', '\327' : '\\327', '\330' : '\\330',309- '\331' : '\\331', '\332' : '\\332', '\333' : '\\333',310- '\334' : '\\334', '\335' : '\\335', '\336' : '\\336',311- '\337' : '\\337', '\340' : '\\340', '\341' : '\\341',312- '\342' : '\\342', '\343' : '\\343', '\344' : '\\344',313- '\345' : '\\345', '\346' : '\\346', '\347' : '\\347',314- '\350' : '\\350', '\351' : '\\351', '\352' : '\\352',315- '\353' : '\\353', '\354' : '\\354', '\355' : '\\355',316- '\356' : '\\356', '\357' : '\\357', '\360' : '\\360',317- '\361' : '\\361', '\362' : '\\362', '\363' : '\\363',318- '\364' : '\\364', '\365' : '\\365', '\366' : '\\366',319- '\367' : '\\367', '\370' : '\\370', '\371' : '\\371',320- '\372' : '\\372', '\373' : '\\373', '\374' : '\\374',321- '\375' : '\\375', '\376' : '\\376', '\377' : '\\377'322- }323-324-_idmap = ''.join(chr(x) for x in range(256))325-326-def _quote(str, LegalChars=_LegalChars,327- idmap=_idmap, translate=string.translate):328- #329- # If the string does not need to be double-quoted,330- # then just return the string. Otherwise, surround331- # the string in doublequotes and precede quote (with a \)332- # special characters.333- #334- if "" == translate(str, idmap, LegalChars):335- return str336- else:337- return '"' + _nulljoin( map(_Translator.get, str, str) ) + '"'338-# end _quote339-340-341-_OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")342-_QuotePatt = re.compile(r"[\\].")343-344-def _unquote(str):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 str349- if str[0] != '"' or str[-1] != '"':350- return str351-352- # We have to assume that we must decode this string.353- # Down to work.354-355- # Remove the "s356- str = str[1:-1]357-358- # Check for special sequences. Examples:359- # \012 --> \n360- # \" --> "361- #362- i = 0363- 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 matched369- res.append(str[i:])370- break371- # else:372- j = k = -1373- if Omatch: j = Omatch.start(0)374- if Qmatch: k = Qmatch.start(0)375- if Qmatch and ( not Omatch or k < j ): # QuotePatt matched376- res.append(str[i:k])377- res.append(str[k+1])378- i = k+2379- else: # OctalPatt matched380- res.append(str[i:j])381- res.append( chr( int(str[j+1:j+4], 8) ) )382- i = j+4383- return _nulljoin(res)384-# end _unquote385-386-# The _getdate() routine is used to set the expiration time in387-# the cookie's HTTP header. By default, _getdate() returns the388-# current time in the appropriate "expires" format for a389-# Set-Cookie header. The one optional argument is an offset from390-# 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, time402- 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 associated412-# with the appropriate key,value pair.413-# This class also includes a coded_value attribute, which414-# is used to hold the network representation of the415-# value. This is most useful when Python objects are416-# pickled for network transit.417-#418-419-class Morsel(dict):420- # RFC 2109 lists these attributes as reserved:421- # path comment domain422- # max-age secure version423- #424- # For historical reasons, these attributes are also reserved:425- # expires426- #427- # This is an extension from Microsoft:428- # httponly429- #430- # This dictionary provides a mapping from the lowercase431- # variant on the left to the appropriate traditional432- # formatting on the right.433- _reserved = { "expires" : "expires",434- "path" : "Path",435- "comment" : "Comment",436- "domain" : "Domain",437- "max-age" : "Max-Age",438- "secure" : "secure",439- "httponly" : "httponly",440- "version" : "Version",441- }442-443- def __init__(self):444- # Set defaults445- self.key = self.value = self.coded_value = None446-447- # Set default attributes448- for K in self._reserved:449- dict.__setitem__(self, K, "")450- # end __init__451-452- def __setitem__(self, K, V):453- K = K.lower()454- if not K in self._reserved:455- raise CookieError("Invalid Attribute %s" % K)456- dict.__setitem__(self, K, V)457- # end __setitem__458-459- def isReservedKey(self, K):460- return K.lower() in self._reserved461- # end isReservedKey462-463- def set(self, key, val, coded_val,464- LegalChars=_LegalChars,465- idmap=_idmap, translate=string.translate):466- # First we verify that the key isn't a reserved word467- # Second we make sure it only contains legal characters468- if key.lower() in self._reserved:469- raise CookieError("Attempt to set a reserved key: %s" % key)470- if "" != translate(key, idmap, LegalChars):471- raise CookieError("Illegal key value: %s" % key)472-473- # It's a good key, so save it.474- self.key = key475- self.value = val476- self.coded_value = coded_val477- # end set478-479- def output(self, attrs=None, header = "Set-Cookie:"):480- return "%s %s" % ( header, self.OutputString(attrs) )481-482- __str__ = output483-484- def __repr__(self):485- return '<%s: %s=%s>' % (self.__class__.__name__,486- self.key, repr(self.value) )487-488- def js_output(self, attrs=None):489- # Print javascript490- return """491- <script type="text/javascript">492- <!-- begin hiding493- document.cookie = \"%s\";494- // end hiding -->495- </script>496- """ % ( self.OutputString(attrs).replace('"',r'\"'), )497- # end js_output()498-499- def OutputString(self, attrs=None):500- # Build up our result501- #502- result = []503- RA = result.append504-505- # First, the key=value pair506- RA("%s=%s" % (self.key, self.coded_value))507-508- # Now add any defined attributes509- if attrs is None:510- attrs = self._reserved511- items = self.items()512- items.sort()513- for K,V in items:514- if V == "": continue515- if K not in attrs: continue516- if K == "expires" and type(V) == type(1):517- RA("%s=%s" % (self._reserved[K], _getdate(V)))518- elif K == "max-age" and type(V) == type(1):519- RA("%s=%d" % (self._reserved[K], V))520- elif K == "secure":521- RA(str(self._reserved[K]))522- elif K == "httponly":523- RA(str(self._reserved[K]))524- else:525- RA("%s=%s" % (self._reserved[K], V))526-527- # Return the result528- return _semispacejoin(result)529- # end OutputString530-# end Morsel class531-532-533-534-#535-# Pattern for finding cookie536-#537-# This used to be strict parsing based on the RFC2109 and RFC2068538-# specifications. I have since discovered that MSIE 3.0x doesn't539-# follow the character rules outlined in those specs. As a540-# result, the parsing rules here are less strict.541-#542-543-_LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=\[\]\_]"544-545-_CookiePattern = re.compile(546- r"(?x)" # This is a Verbose pattern547- r"(?P<key>" # Start of group 'key'548- ""+ _LegalCharsPatt +"+?" # Any word of at least one letter, nongreedy549- r")" # End of group 'key'550- r"\s*=\s*" # Equal Sign551- r"(?P<val>" # Start of group 'val'552- r'"(?:[^\\"]|\\.)*"' # Any doublequoted string553- r"|" # or554- r"\w{3},\s[\w\d-]{9,11}\s[\d:]{8}\sGMT" # Special case for "expires" attr555- r"|" # or556- ""+ _LegalCharsPatt +"*" # Any word or empty string557- r")" # End of group 'val'558- r"\s*;?" # Probably ending in a semi-colon559- )560-561-562-# At long last, here is the cookie class.563-# Using this class is almost just like using a dictionary.564-# See this module's docstring for example usage.565-#566-class BaseCookie(dict):567- # A container class for a set of Morsels568- #569-570- def value_decode(self, val):571- """real_value, coded_value = value_decode(STRING)572- Called prior to setting a cookie's value from the network573- representation. The VALUE is the value read from HTTP574- header.575- Override this function to modify the behavior of cookies.576- """577- return val, val578- # end value_encode579-580- def value_encode(self, val):581- """real_value, coded_value = value_encode(VALUE)582- Called prior to setting a cookie's value from the dictionary583- representation. The VALUE is the value being assigned.584- Override this function to modify the behavior of cookies.585- """586- strval = str(val)587- return strval, strval588- # end value_encode589-590- def __init__(self, input=None):591- if input: self.load(input)592- # end __init__593-594- def __set(self, key, real_value, coded_value):595- """Private method for setting a cookie's value"""596- M = self.get(key, Morsel())597- M.set(key, real_value, coded_value)598- dict.__setitem__(self, key, M)599- # end __set600-601- def __setitem__(self, key, value):602- """Dictionary style assignment."""603- rval, cval = self.value_encode(value)604- self.__set(key, rval, cval)605- # end __setitem__606-607- def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):608- """Return a string suitable for HTTP."""609- result = []610- items = self.items()611- items.sort()612- for K,V in items:613- result.append( V.output(attrs, header) )614- return sep.join(result)615- # end output616-617- __str__ = output618-619- def __repr__(self):620- L = []621- items = self.items()622- items.sort()623- for K,V in items:624- L.append( '%s=%s' % (K,repr(V.value) ) )625- return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))626-627- def js_output(self, attrs=None):628- """Return a string suitable for JavaScript."""629- result = []630- items = self.items()631- items.sort()632- for K,V in items:633- result.append( V.js_output(attrs) )634- return _nulljoin(result)635- # end js_output636-637- def load(self, rawdata):638- """Load cookies from a string (presumably HTTP_COOKIE) or639- from a dictionary. Loading cookies from a dictionary 'd'640- is equivalent to calling:641- map(Cookie.__setitem__, d.keys(), d.values())642- """643- if type(rawdata) == type(""):644- self.__ParseString(rawdata)645- else:646- # self.update() wouldn't call our custom __setitem__647- for k, v in rawdata.items():648- self[k] = v649- return650- # end load()651-652- def __ParseString(self, str, patt=_CookiePattern):653- i = 0 # Our starting point654- n = len(str) # Length of string655- M = None # current morsel656-657- while 0 <= i < n:658- # Start looking for a cookie659- match = patt.search(str, i)660- if not match: break # No more cookies661-662- K,V = match.group("key"), match.group("val")663- i = match.end(0)664-665- # Parse the key, value in case it's metainfo666- if K[0] == "$":667- # We ignore attributes which pertain to the cookie668- # mechanism as a whole. See RFC 2109.669- # (Does anyone care?)670- if M:671- M[ K[1:] ] = V672- elif K.lower() in Morsel._reserved:673- if M:674- M[ K ] = _unquote(V)675- else:676- rval, cval = self.value_decode(V)677- self.__set(K, rval, cval)678- M = self[K]679- # end __ParseString680-# end BaseCookie class681-682-class SimpleCookie(BaseCookie):683- """SimpleCookie684- SimpleCookie supports strings as cookie values. When setting685- the value using the dictionary assignment notation, SimpleCookie686- calls the builtin str() to convert the value to a string. Values687- received from HTTP are kept as strings.688- """689- def value_decode(self, val):690- return _unquote( val ), val691- def value_encode(self, val):692- strval = str(val)693- return strval, _quote( strval )694-# end SimpleCookie695-696-class SerialCookie(BaseCookie):697- """SerialCookie698- SerialCookie supports arbitrary objects as cookie values. All699- values are serialized (using cPickle) before being sent to the700- client. All incoming values are assumed to be valid Pickle701- representations. IF AN INCOMING VALUE IS NOT IN A VALID PICKLE702- FORMAT, THEN AN EXCEPTION WILL BE RAISED.703-704- Note: Large cookie values add overhead because they must be705- retransmitted on every HTTP transaction.706-707- Note: HTTP has a 2k limit on the size of a cookie. This class708- does not check for this limit, so be careful!!!709- """710- def __init__(self, input=None):711- warnings.warn("SerialCookie class is insecure; do not use it",712- DeprecationWarning)713- BaseCookie.__init__(self, input)714- # end __init__715- def value_decode(self, val):716- # This could raise an exception!717- return loads( _unquote(val) ), val718- def value_encode(self, val):719- return val, _quote( dumps(val) )720-# end SerialCookie721-722-class SmartCookie(BaseCookie):723- """SmartCookie724- SmartCookie supports arbitrary objects as cookie values. If the725- object is a string, then it is quoted. If the object is not a726- string, however, then SmartCookie will use cPickle to serialize727- the object into a string representation.728-729- Note: Large cookie values add overhead because they must be730- retransmitted on every HTTP transaction.731-732- Note: HTTP has a 2k limit on the size of a cookie. This class733- does not check for this limit, so be careful!!!734- """735- def __init__(self, input=None):736- warnings.warn("Cookie/SmartCookie class is insecure; do not use it",737- DeprecationWarning)738- BaseCookie.__init__(self, input)739- # end __init__740- def value_decode(self, val):741- strval = _unquote(val)742- try:743- return loads(strval), val744- except:745- return strval, val746- def value_encode(self, val):747- if type(val) == type(""):748- return val, _quote(val)749- else:750- return val, _quote( dumps(val) )751-# end SmartCookie752-753-754-###########################################################755-# Backwards Compatibility: Don't break any existing code!756-757-# We provide Cookie() as an alias for SmartCookie()758-Cookie = SmartCookie759-760-#761-###########################################################762-763-def _test():764- import doctest, Cookie765- return doctest.testmod(Cookie)766-767-if __name__ == "__main__":768- _test()769-770-771-#Local Variables:772-#tab-width: 4773-#end:deleted:requests/packages/oreos/structures.py-399 removed
1-# -*- coding: utf-8 -*-2-3-"""4-oreos.structures5-~~~~~~~~~~~~~~~~6-7-The plastic blue packaging.8-9-This is mostly directly stolen from mitsuhiko/werkzeug.10-"""11-12-__all__ = ('MultiDict',)13-14-class _Missing(object):15-16- def __repr__(self):17- return 'no value'18-19- def __reduce__(self):20- return '_missing'21-22-_missing = _Missing()23-24-25-26-def 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 item43-44-45-46-class 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.50-51- .. versionadded:: 0.552- """53-54- 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:60-61- >>> d = TypeConversionDict(foo='42', bar='blub')62- >>> d.get('foo', type=int)63- 4264- >>> d.get('bar', -1, type=int)65- -166-67- :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 rv82-83-84-class 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.89-90- :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.95-96- Basic Usage:97-98- >>> 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- True107-108- It behaves like a normal dict thus all dict functions will only return the109- first value when multiple values for one key are found.110-111- 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.115-116- 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.119-120- :param mapping: the initial value for the :class:`MultiDict`. Either a121- regular dict, an iterable of ``(key, value)`` tuples122- or `None`.123- """124-125- 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)142-143- def __getstate__(self):144- return dict(self.lists())145-146- def __setstate__(self, value):147- dict.clear(self)148- dict.update(self, value)149-150- def __iter__(self):151- return self.iterkeys()152-153- def __getitem__(self, key):154- """Return the first data value for this key;155- raises KeyError if not found.156-157- :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)163-164- def __setitem__(self, key, value):165- """Like :meth:`add` but removes an existing key first.166-167- :param key: the key for the value.168- :param value: the value to set.169- """170- dict.__setitem__(self, key, [value])171-172- def add(self, key, value):173- """Adds a new value for the key.174-175- .. versionadded:: 0.6176-177- :param key: the key for the value.178- :param value: the value to add.179- """180- dict.setdefault(self, key, []).append(value)181-182- 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.187-188- :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 result207-208- 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.212-213- >>> d = MultiDict()214- >>> d.setlist('foo', ['1', '2'])215- >>> d['foo']216- '1'217- >>> d.getlist('foo')218- ['1', '2']219-220- :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))225-226- 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`.229-230- :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 default239-240- 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:245-246- >>> d = MultiDict({"foo": 1})247- >>> d.setlistdefault("foo").extend([2, 3])248- >>> d.getlist("foo")249- [1, 2, 3]250-251- :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_list263-264- def items(self, multi=False):265- """Return a list of ``(key, value)`` pairs.266-267- :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.271-272- :return: a :class:`list`273- """274- return list(self.iteritems(multi))275-276- def lists(self):277- """Return a list of ``(key, values)`` pairs, where values is the list of278- all values associated with the key.279-280- :return: a :class:`list`281- """282- return list(self.iterlists())283-284- def values(self):285- """Returns a list of the first value on every key's value list.286-287- :return: a :class:`list`.288- """289- return [self[key] for key in self.iterkeys()]290-291- 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`:294-295- >>> d = MultiDict({"foo": [1, 2, 3]})296- >>> zip(d.keys(), d.listvalues()) == d.lists()297- True298-299- :return: a :class:`list`300- """301- return list(self.iterlistvalues())302-303- 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]311-312- def iterlists(self):313- """Like :meth:`items` but returns an iterator."""314- for key, values in dict.iteritems(self):315- yield key, list(values)316-317- def itervalues(self):318- """Like :meth:`values` but returns an iterator."""319- for values in dict.itervalues(self):320- yield values[0]321-322- def iterlistvalues(self):323- """Like :meth:`listvalues` but returns an iterator."""324- return dict.itervalues(self)325-326- def copy(self):327- """Return a shallow copy of this object."""328- return self.__class__(self)329-330- 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.334-335- :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())343-344- 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)348-349- 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:352-353- >>> d = MultiDict({"foo": [1, 2, 3]})354- >>> d.pop("foo")355- 1356- >>> "foo" in d357- False358-359- :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 as e:366- if default is not _missing:367- return default368- raise KeyError(str(e))369-370- 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 as e:376- raise KeyError(str(e))377-378- 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.381-382- .. 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, [])387-388- def popitemlist(self):389- """Pop a ``(key, list)`` tuple from the dict."""390- try:391- return dict.popitem(self)392- except KeyError as e:393- raise KeyError(str(e))394-395- def __copy__(self):396- return self.copy()397-398- def __repr__(self):399- return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))