Merge branch 'develop'
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 · parents 1165bec, ab23536 · Browse files · 18 files·+1398 added−155 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+1398 added−155 removed
- other:+1398 added−155 removed
Provenance
- Commit
42b33ae- Tree
859ec7b- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
1165bec- Parent 2
ab23536
18 files changed+1398 added−155 removed
modified:docs/dev/authors.rst+1 added-1 removed
1 Authors2 =======3 4 5-.. include:: ../../AUTHORS5+.. include:: ../../AUTHORS.rstmodified:docs/user/advanced.rst+1 added-1 removed
76 unmodified lines77 78 Keep-Alive79 ----------80 81-Excellent news — thanks to urllib3. keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!81+Excellent news — thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!82 83 If you'd like to disable keep-alive, you can simply set the ``keep_alive`` configuration to ``False``::84 85 s = requests.session()169 unmodified linesmodified:docs/user/quickstart.rst+30 added
40 unmodified lines41 42 Requests does its best to decode content from the server. Most unicode43 charsets, ``gzip``, and ``deflate`` encodings are all seamlessly decoded.44 45+When you make a request, ``r.encoding`` is set, based on the HTTP headers.46+Requests will attempt to use that encoding when you access ``r.content``. You47+can manually set ``r.encoding`` to any encoding you'd like (including ``None``),48+and that charset will be used.49 50+51 Make a POST Request52 -------------------53 54 POST requests are equally simple::81 unmodified lines136 },137 "data": ""138 }139 140+Setting filename explicitly::141 142+ >>> url = 'http://httpbin.org/post'143+ >>> files = {'file': ('report.xls', open('report.xls', 'rb'))}144 145+ >>> r = requests.post(url, files=files)146+ >>> r.content147+ {148+ "origin": "179.13.100.4",149+ "files": {150+ "file": "<censored...binary...data>"151+ },152+ "form": {},153+ "url": "http://httpbin.org/post",154+ "args": {},155+ "headers": {156+ "Content-Length": "3196",157+ "Accept-Encoding": "identity, deflate, compress, gzip",158+ "Accept": "*/*",159+ "User-Agent": "python-requests/0.8.0",160+ "Host": "httpbin.org:80",161+ "Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"162+ },163+ "data": ""164+ }165+166+167 Response Status Codes168 ---------------------169 170 We can check the response status code::186 unmodified linesmodified:docs/index.rst+30 added-16 removed
8 unmodified lines9 Release v\ |version|. (:ref:`Installation <install>`)10 11 Requests is an :ref:`ISC Licensed <isc>` HTTP library, written in Python, for human beings.12 13-Most existing Python modules for sending HTTP requests are extremely verbose14-and cumbersome. Python's builtin **urllib2** module provides most of15-the HTTP capabilities you should need, but the api is thoroughly **broken**.16-It requires an *enormous* amount of work (even method overrides) to perform17-the simplest of tasks.13+Python's standard **urllib2** module provides most of14+the HTTP capabilities you need, but the API is thoroughly **broken**.15+It was built for a different time — and a different web. It requires an *enormous* amount of work (even method overrides) to perform the simplest of tasks.16 17 Things shouldn’t be this way. Not in Python.18 19 ::7 unmodified lines27 ...28 29 See `the same code, without Requests <https://gist.github.com/973705>`_.30 33-Requests allows you to send **HEAD**, **GET**, **POST**, **PUT**,34-**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,35-multipart files, and parameters with simple Python dictionaries, and access the36-response data in the same way. It's powered by :py:class:`httplib` and :py:class:`urllib3`, and it strives to be as elegant and approachable as possible.31+Requests takes all of the work out of Python HTTP — making your integration with web services seamless. There's no need to manually add query strings to your URLs, or to form-encode your POST data.32 33+34 Testimonials35 ------------36 41-`The Washington Post <http://www.washingtonpost.com/>`_, `Twitter, Inc <http://twitter.com>`_,42-a U.S. Federal Institution,43-NIH,37+`The Washington Post <http://www.washingtonpost.com/>`_,38+`Twitter, Inc <http://twitter.com>`_,39 `Readability <http://readability.com>`_, and45-`Work for Pie <http://workforpie.com>`_46-use Requests internally.40+Federal US Institutions41+use Requests internally. It has been installed over 45,000 times from PyPi.42 43 **Armin Ronacher**44 Requests is the perfect example how beautiful an API can be with the45 right level of abstraction.46 47+**Matt DeBoard**48+ I'm going to get @kennethreitz's Python requests module tattooed49+ on my body, somehow. The whole thing.50+51 **Daniel Greenfeld**52 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to53 @kennethreitz's request library. Today has been AWESOME.54 55 **Kenny Meyers**56 Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,57 simple, Pythonic.58 60-**Rich Leland**61- Requests is awesome. That is all.59 60+Feature Support61+---------------62 63+Requests is ready for today's web.64+65+- International Domains and URLs66+- Keep-Alive & Connection Pooling67+- Sessions with Cookie Persistence68+- Basic/Digest Authentication69+- Elegant Key/Value Cookies70+- Automatic Decompression71+- Unicode Response Bodies72+- Multipart File Uploads73+- Connection Timeouts74+- Zero Dependencies75+76+77+78 User Guide79 ----------80 81 This part of the documentation, which is mostly prose, begins with some50 unmodified linesadded:requests/packages/oreos/__init__.py+3 added
1+# -*- coding: utf-8 -*-2+3+from .core import dict_from_stringadded:requests/packages/oreos/core.py+24 added
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 cookiesadded:requests/packages/oreos/monkeys.py+770 added
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+# _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',268+269+ # Because of the way browsers really handle cookies (as opposed270+ # to what the RFC says) we also encode , and ;271+272+ ',' : '\\054', ';' : '\\073',273+274+ '"' : '\\"', '\\' : '\\\\',275+276+ '\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+ }320+321+_idmap = ''.join(chr(x) for x in xrange(256))322+323+def _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 _quote336+337+338+_OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")339+_QuotePatt = re.compile(r"[\\].")340+341+def _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 str348+349+ # We have to assume that we must decode this string.350+ # Down to work.351+352+ # Remove the "s353+ str = str[1:-1]354+355+ # 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 _unquote382+383+# 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+#390+391+_weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']392+393+_monthname = [None,394+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',395+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']396+397+def _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)403+404+405+#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+#415+416+class 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+ }439+440+ def __init__(self):441+ # Set defaults442+ self.key = self.value = self.coded_value = None443+444+ # Set default attributes445+ for K in self._reserved:446+ dict.__setitem__(self, K, "")447+ # end __init__448+449+ 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__455+456+ def isReservedKey(self, K):457+ return K.lower() in self._reserved458+ # end isReservedKey459+460+ 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)469+470+ # It's a good key, so save it.471+ self.key = key472+ self.value = val473+ self.coded_value = coded_val474+ # end set475+476+ def output(self, attrs=None, header = "Set-Cookie:"):477+ return "%s %s" % ( header, self.OutputString(attrs) )478+479+ __str__ = output480+481+ def __repr__(self):482+ return '<%s: %s=%s>' % (self.__class__.__name__,483+ self.key, repr(self.value) )484+485+ 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()495+496+ def OutputString(self, attrs=None):497+ # Build up our result498+ #499+ result = []500+ RA = result.append501+502+ # First, the key=value pair503+ RA("%s=%s" % (self.key, self.coded_value))504+505+ # 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))523+524+ # Return the result525+ return _semispacejoin(result)526+ # end OutputString527+# end Morsel class528+529+530+531+#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+#539+540+_LegalCharsPatt = r"[\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=\[\]\_]"541+542+_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+ )557+558+559+# 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+#563+class BaseCookie(dict):564+ # A container class for a set of Morsels565+ #566+567+ 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_encode576+577+ 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_encode586+587+ def __init__(self, input=None):588+ if input: self.load(input)589+ # end __init__590+591+ 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 __set597+598+ 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__603+604+ 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 output613+614+ __str__ = output615+616+ 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))623+624+ 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_output633+634+ 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()648+649+ def __ParseString(self, str, patt=_CookiePattern):650+ i = 0 # Our starting point651+ n = len(str) # Length of string652+ M = None # current morsel653+654+ while 0 <= i < n:655+ # Start looking for a cookie656+ match = patt.search(str, i)657+ if not match: break # No more cookies658+659+ K,V = match.group("key"), match.group("val")660+ i = match.end(0)661+662+ # 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 class678+679+class 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 SimpleCookie692+693+class 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.700+701+ Note: Large cookie values add overhead because they must be702+ retransmitted on every HTTP transaction.703+704+ 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 SerialCookie718+719+class 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.725+726+ Note: Large cookie values add overhead because they must be727+ retransmitted on every HTTP transaction.728+729+ 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 SmartCookie749+750+751+###########################################################752+# Backwards Compatibility: Don't break any existing code!753+754+# We provide Cookie() as an alias for SmartCookie()755+Cookie = SmartCookie756+757+#758+###########################################################759+760+def _test():761+ import doctest, Cookie762+ return doctest.testmod(Cookie)763+764+if __name__ == "__main__":765+ _test()766+767+768+#Local Variables:769+#tab-width: 4770+#end:added:requests/packages/oreos/structures.py+399 added
1+# -*- coding: utf-8 -*-2+3+"""4+oreos.sructures5+~~~~~~~~~~~~~~~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, 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, 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, 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))modified:requests/packages/urllib3/connectionpool.py+1 added-1 removed
336 unmodified lines337 # ``response.read()``)338 339 except (SocketTimeout, Empty), e:340 # Timed out either by socket or queue341- raise TimeoutError("Request timed out after %f seconds" %341+ raise TimeoutError("Request timed out after %s seconds" %342 self.timeout)343 344 except (BaseSSLError), e:345 # SSL certificate error180 unmodified linesmodified:requests/__init__.py+2 added-2 removed
13 unmodified lines14 15 """16 17 __title__ = 'requests'18-__version__ = '0.8.1'19-__build__ = 0x00080118+__version__ = '0.8.2'19+__build__ = 0x00080220 __author__ = 'Kenneth Reitz'21 __license__ = 'ISC'22 __copyright__ = 'Copyright 2011 Kenneth Reitz'23 10 unmodified linesmodified:requests/api.py+1 added-1 removed
35 unmodified lines36 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.37 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.38 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.39 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.40- :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.40+ :param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.41 :param auth: (optional) Auth typle to enable Basic/Digest/Custom HTTP Auth.42 :param timeout: (optional) Float describing the timeout of the request.43 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.44 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.99 unmodified linesmodified:requests/models.py+47 added-30 removed
8 unmodified lines9 10 import urllib11 import zlib12 13-from Cookie import SimpleCookie13 from urlparse import urlparse, urlunparse, urljoin, urlsplit14 from datetime import datetime15 16 from .auth import dispatch as auth_dispatch17 from .hooks import dispatch_hook18 from .structures import CaseInsensitiveDict19 from .status_codes import codes20+from .packages import oreos21 from .packages.urllib3.exceptions import MaxRetryError22 from .packages.urllib3.exceptions import SSLError as _SSLError23 from .packages.urllib3.exceptions import HTTPError as _HTTPError24 from .packages.urllib3 import connectionpool, poolmanager25 from .packages.urllib3.filepost import encode_multipart_formdata26 from .exceptions import (27 Timeout, URLRequired, TooManyRedirects, HTTPError, ConnectionError)28 from .utils import (29- get_unicode_from_response, stream_decode_response_unicode,30- decode_gzip, stream_decode_gzip, guess_filename)29+ get_encoding_from_headers, stream_decode_response_unicode,30+ decode_gzip, stream_decode_gzip, guess_filename, requote_path)31 32 33 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)34 107 unmodified lines142 """Build internal :class:`Response <Response>` object143 from given response.144 """145 146-146 def build(resp):147 148 response = Response()149 7 unmodified lines157 158 # Make headers case-insensitive.159 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))160 161+ # Set encoding.162+ response.encoding = get_encoding_from_headers(response.headers)163+164 # Start off with our local cookies.165 cookies = self.cookies or dict()166 167 # Add new cookies from the server.168 if 'set-cookie' in response.headers:169 cookie_header = response.headers['set-cookie']170+ cookies = oreos.dict_from_string(cookie_header)171 169- c = SimpleCookie()170- c.load(cookie_header)171-172- for k,v in c.items():173- cookies.update({k: v.value})174-172 # Save cookies in Response.173 response.cookies = cookies174 175 # Save original resopnse for later.5 unmodified lines181 response.url = self.full_url182 183 return response184 188-185 history = []186 187 r = build(resp)188 cookies = self.cookies20 unmodified lines209 210 # Facilitate non-RFC2616-compliant 'location' headers211 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')212 if not urlparse(url).netloc:217- url = urljoin(r.url, urllib.quote(urllib.unquote(url)))213+ url = urljoin(r.url, url)214 215 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4216 if r.status_code is codes.see_other:217 method = 'GET'76 unmodified lines294 295 if isinstance(path, unicode):296 path = path.encode('utf-8')297 302- path = urllib.quote(urllib.unquote(path))298+ path = requote_path(path)299 300 url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))301 302 if self._enc_params:63 unmodified lines366 except AttributeError:367 fields = dict(self.data)368 369 for (k, v) in self.files.items():370+ # support for explicit filename371+ if isinstance(v, (tuple, list)):372+ fn, fp = v373+ else:374+ fn = guess_filename(v) or k375+ fp = v374- fields.update({k: (guess_filename(k) or k, v.read())})376+ fields.update({k: (fn, fp.read())})377 378 (body, content_type) = encode_multipart_formdata(fields)379 else:380 pass40 unmodified lines421 # Skip if 'cookie' header is explicitly set.422 if 'cookie' not in self.headers:423 424 # Simple cookie with our dict.423- c = SimpleCookie()425+ c = oreos.monkeys.SimpleCookie()426 for (k, v) in self.cookies.items():427 c[k] = v428 429 # Turn it into a header.428- cookie_header = c.output(header='').strip()430+ cookie_header = c.output(header='', sep='; ').strip()431 432 # Attach Cookie header to request.433 self.headers['Cookie'] = cookie_header434 67 unmodified lines502 503 #: Resulting :class:`HTTPError` of request, if one occurred.504 self.error = None505 506+ #: Encoding to decode with when accessing r.content.507+ self.encoding = None508+509 #: A list of :class:`Response <Response>` objects from510 #: the history of the Request. Any redirect responses will end511 #: up here.512 self.history = []62 unmodified lines575 """Content of the response, in bytes or unicode576 (if available).577 """578 574- if self._content is not None:575- return self._content579+ if self._content is None:580+ # Read the contents.581+ try:582+ if self._content_consumed:583+ raise RuntimeError(584+ 'The content for this response was already consumed')585 577- if self._content_consumed:578- raise RuntimeError('The content for this response was '579- 'already consumed')586+ self._content = self.raw.read()587+ except AttributeError:588+ self._content = None589 581- # Read the contents.582- try:583- self._content = self.raw.read()584- except AttributeError:585- return None590+ content = self._content591 587-592 # Decode GZip'd content.593 if 'gzip' in self.headers.get('content-encoding', ''):594 try:591- self._content = decode_gzip(self._content)595+ content = decode_gzip(self._content)596 except zlib.error:597 pass598 599 # Decode unicode content.600 if self.config.get('decode_unicode'):597- self._content = get_unicode_from_response(self)601 602+ # Try charset from content-type603+604+ if self.encoding:605+ try:606+ content = unicode(content, self.encoding)607+ except UnicodeError:608+ pass609+610+ # Fall back:611+ try:612+ content = unicode(content, self.encoding, errors='replace')613+ except TypeError:614+ pass615+616 self._content_consumed = True600- return self._content617+ return content618 619 620 def raise_for_status(self):621 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""14 unmodified linesdeleted:requests/monkeys.py-39 removed
1-#-*- coding: utf-8 -*-2-3-"""4-requests.monkeys5-~~~~~~~~~~~~~~~~6-7-Urllib2 Monkey patches.8-9-"""10-11-import urllib212-import re13-14-class Request(urllib2.Request):15- """Hidden wrapper around the urllib2.Request object. Allows for manual16- setting of HTTP methods.17- """18-19- def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):20- urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)21- self.method = method22-23- def get_method(self):24- if self.method:25- return self.method26-27- return urllib2.Request.get_method(self)28-29-30-class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):31- """HTTP Redirect handler."""32- def _pass(self, req, fp, code, msg, headers):33- pass34-35- http_error_302 = _pass36- http_error_303 = _pass37- http_error_307 = _pass38- http_error_301 = _pass39-modified:requests/sessions.py+4 added
138 unmodified lines139 data = {} if data is None else data140 files = {} if files is None else files141 headers = {} if headers is None else headers142 params = {} if params is None else params143+ hooks = {} if hooks is None else hooks144+ # use session's hooks as defaults145+ for key, cb in self.hooks.iteritems():146+ hooks.setdefault(key, cb)147 148 # Expand header values.149 if headers:150 for k, v in headers.items() or {}:129 unmodified linesmodified:requests/utils.py+15 added-3 removed
14 unmodified lines15 import os16 import random17 import re18 import zlib19+import urllib20 21 from urllib2 import parse_http_list as _parse_list_header22 23 271 unmodified lines295 296 297 def stream_decode_response_unicode(iterator, r):298 """Stream decodes a iterator."""298- encoding = get_encoding_from_headers(r.headers)299- if encoding is None:299+300+ if r.encoding is None:301 for item in iterator:302 yield item303 return304 304- decoder = codecs.getincrementaldecoder(encoding)(errors='replace')305+ decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')306 for chunk in iterator:307 rv = decoder.decode(chunk)308 if rv:309 yield rv57 unmodified lines367 if rv:368 yield rv369 except zlib.error:370 pass371+372+373+def requote_path(path):374+ """Re-quote the given URL path component.375+376+ This function passes the given path through an unquote/quote cycle to377+ ensure that it is fully and consistenty quoted.378+ """379+ parts = path.split("/")380+ parts = (urllib.quote(urllib.unquote(part), safe="") for part in parts)381+ return "/".join(parts)deleted:AUTHORS-61 removed
1-Requests is written and maintained by Kenneth Reitz and2-various contributors:3-4-Development Lead5-````````````````6-7-- Kenneth Reitz <me@kennethreitz.com>8-9-10-Urllib311-```````12-13-- Andrey Petrov <andrey.petrov@shazow.net>14-15-16-Patches and Suggestions17-```````````````````````18-19-- Various Pocoo Members20-- Chris Adams21-- Flavio Percoco Premoli22-- Dj Gilcrease23-- Justin Murphy24-- Rob Madole25-- Aram Dulyan26-- Johannes Gorset27-- 村山めがね (Megane Murayama)28-- James Rowe29-- Daniel Schauenberg30-- Zbigniew Siciarz31-- Daniele Tricoli 'Eriol'32-- Richard Boulton33-- Miguel Olivares <miguel@moliware.com>34-- Alberto Paro35-- Jérémy Bethmont36-- 潘旭 (Xu Pan)37-- Tamás Gulácsi38-- Rubén Abad39-- Peter Manser40-- Jeremy Selier41-- Jens Diemer42-- Alex <@alopatin>43-- Tom Hogans <tomhsx@gmail.com>44-- Armin Ronacher45-- Shrikant Sharat Kandula46-- Mikko Ohtamaa47-- Den Shabalin48-- Daniel Miller <danielm@vs-networks.com>49-- Alejandro Giacometti50-- Rick Mak51-- Johan Bergström52-- Josselin Jacquard53-- Travis N. Vaught54-- Fredrik Möllerstrand55-- Daniel Hengeveld56-- Dan Head57-- Bruno Renié58-- David Fischer59-- Joseph McCullough60-- Juergen Brendel61-- Juan Riazaadded:AUTHORS.rst+63 added
1+Requests is written and maintained by Kenneth Reitz and2+various contributors:3+4+Development Lead5+````````````````6+7+- Kenneth Reitz <me@kennethreitz.com>8+9+10+Urllib311+```````12+13+- Andrey Petrov <andrey.petrov@shazow.net>14+15+16+Patches and Suggestions17+```````````````````````18+19+- Various Pocoo Members20+- Chris Adams21+- Flavio Percoco Premoli22+- Dj Gilcrease23+- Justin Murphy24+- Rob Madole25+- Aram Dulyan26+- Johannes Gorset27+- 村山めがね (Megane Murayama)28+- James Rowe29+- Daniel Schauenberg30+- Zbigniew Siciarz31+- Daniele Tricoli 'Eriol'32+- Richard Boulton33+- Miguel Olivares <miguel@moliware.com>34+- Alberto Paro35+- Jérémy Bethmont36+- 潘旭 (Xu Pan)37+- Tamás Gulácsi38+- Rubén Abad39+- Peter Manser40+- Jeremy Selier41+- Jens Diemer42+- Alex <@alopatin>43+- Tom Hogans <tomhsx@gmail.com>44+- Armin Ronacher45+- Shrikant Sharat Kandula46+- Mikko Ohtamaa47+- Den Shabalin48+- Daniel Miller <danielm@vs-networks.com>49+- Alejandro Giacometti50+- Rick Mak51+- Johan Bergström52+- Josselin Jacquard53+- Travis N. Vaught54+- Fredrik Möllerstrand55+- Daniel Hengeveld56+- Dan Head57+- Bruno Renié58+- David Fischer59+- Joseph McCullough60+- Juergen Brendel61+- Juan Riaza62+- Ryan Kelly63+- Rolando Espinoza La fuentemodified:HISTORY.rst+7 added
1 History2 -------3 4+0.8.2 (2011-11-19)5+++++++++++++++++++6+7+* New unicode decoding system, based on overridable `Response.encoding`.8+* Proper URL slash-quote handling.9+* Cookies with ``[``, ``]``, and ``_`` allowed.10+11 0.8.1 (2011-11-15)12 ++++++++++++++++++13 14 * URL Request path fix255 unmodified lines