Merge remote-tracking branch 'upstream/develop' into refactor-urls
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: requests/models.py
authored by Jérémy Bethmont · committed by Jérémy Bethmont · parents ffde764, 1997dee · Browse files · 32 files·+1661 added−1330 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
32 files+1661 added−1330 removed
- other:+1661 added−1330 removed
Provenance
- Commit
7077272- Tree
dd604f6- Author
Jérémy Bethmont <jeremy.bethmont@gmail.com>- Committer
Jérémy Bethmont <jeremy.bethmont@gmail.com>- Parent 1
ffde764- Parent 2
1997dee
32 files changed+1661 added−1330 removed
deleted:debian/changelog-5 removed
1-python-requests (0.4.1-0) testing; urgency=low2-3- * Initial Debian package4-5- -- Bruno Clermont <bruno.clermont@gmail.com> Thu, 26 May 2011 16:25:00 -0500deleted:debian/compat-1 removed
1-5deleted:debian/control-13 removed
1-Source: python-requests2-Section: python3-Priority: optional4-Maintainer: Bruno Clermont <bruno.clermont@gmail.com>5-Homepage: https://github.com/bclermont/requests6-Bugs: https://github.com/bclermont/requests/issues7-Build-Depends: debhelper, python-support8-9-Package: python-requests10-Architecture: all11-Depends: ${python:Depends}, python-support12-Provides: ${python:Provides}13-Description: Python HTTP Requests for Humans.deleted:debian/docs-1 removed
1-docs/user/*.rstdeleted:debian/pyversions-1 removed
1-2.4-deleted:debian/rules-42 removed
1-#!/usr/bin/make -f2-3-# Verbose mode4-#export DH_VERBOSE=15-6-clean:7- dh_testdir8- dh_testroot9-10- rm -rf build requests.egg-info11-# find django-sentry/ -name *.pyc | xargs rm -f12-13- dh_clean14-15-build:16- dh_testdir17-18- python setup.py build19-20-install:21- dh_testdir22- dh_installdirs23-24- python setup.py install --root $(CURDIR)/debian/python-requests25-26-binary-indep: install27-28-binary-arch: install29- dh_install30- dh_installdocs31-# dh_installchangelogs32- dh_compress33- dh_fixperms34- dh_pysupport35- dh_gencontrol36- dh_installdeb37- dh_md5sums38- dh_builddeb -- -Z lzma -z939-40-binary: binary-indep binary-arch41-.PHONY: build clean binary-indep binary-arch binary42-deleted:requests/packages/poster/__init__.py-34 removed
1-# Copyright (c) 2010 Chris AtLee2-# 3-# Permission is hereby granted, free of charge, to any person obtaining a copy4-# of this software and associated documentation files (the "Software"), to deal5-# in the Software without restriction, including without limitation the rights6-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell7-# copies of the Software, and to permit persons to whom the Software is8-# furnished to do so, subject to the following conditions:9-# 10-# The above copyright notice and this permission notice shall be included in11-# all copies or substantial portions of the Software.12-# 13-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,18-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN19-# THE SOFTWARE.20-"""poster module21-22-Support for streaming HTTP uploads, and multipart/form-data encoding23-24-```poster.version``` is a 3-tuple of integers representing the version number.25-New releases of poster will always have a version number that compares greater26-than an older version of poster.27-New in version 0.6."""28-29-from __future__ import absolute_import30-31-from . import streaminghttp32-from . import encode33-34-version = (0, 8, 0) # Thanks JP!deleted:requests/packages/poster/encode.py-414 removed
1-"""multipart/form-data encoding module2-3-This module provides functions that faciliate encoding name/value pairs4-as multipart/form-data suitable for a HTTP POST or PUT request.5-6-multipart/form-data is the standard way to upload files over HTTP"""7-8-__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',9- 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',10- 'multipart_encode']11-12-try:13- import uuid14- def gen_boundary():15- """Returns a random string to use as the boundary for a message"""16- return uuid.uuid4().hex17-except ImportError:18- import random, sha19- def gen_boundary():20- """Returns a random string to use as the boundary for a message"""21- bits = random.getrandbits(160)22- return sha.new(str(bits)).hexdigest()23-24-import urllib, re, os, mimetypes25-try:26- from email.header import Header27-except ImportError:28- # Python 2.429- from email.Header import Header30-31-def encode_and_quote(data):32- """If ``data`` is unicode, return urllib.quote_plus(data.encode("utf-8"))33- otherwise return urllib.quote_plus(data)"""34- if data is None:35- return None36-37- if isinstance(data, unicode):38- data = data.encode("utf-8")39- return urllib.quote_plus(data)40-41-def _strify(s):42- """If s is a unicode string, encode it to UTF-8 and return the results,43- otherwise return str(s), or None if s is None"""44- if s is None:45- return None46- if isinstance(s, unicode):47- return s.encode("utf-8")48- return str(s)49-50-class MultipartParam(object):51- """Represents a single parameter in a multipart/form-data request52-53- ``name`` is the name of this parameter.54-55- If ``value`` is set, it must be a string or unicode object to use as the56- data for this parameter.57-58- If ``filename`` is set, it is what to say that this parameter's filename59- is. Note that this does not have to be the actual filename any local file.60-61- If ``filetype`` is set, it is used as the Content-Type for this parameter.62- If unset it defaults to "text/plain; charset=utf8"63-64- If ``filesize`` is set, it specifies the length of the file ``fileobj``65-66- If ``fileobj`` is set, it must be a file-like object that supports67- .read().68-69- Both ``value`` and ``fileobj`` must not be set, doing so will70- raise a ValueError assertion.71-72- If ``fileobj`` is set, and ``filesize`` is not specified, then73- the file's size will be determined first by stat'ing ``fileobj``'s74- file descriptor, and if that fails, by seeking to the end of the file,75- recording the current position as the size, and then by seeking back to the76- beginning of the file.77-78- ``cb`` is a callable which will be called from iter_encode with (self,79- current, total), representing the current parameter, current amount80- transferred, and the total size.81- """82- def __init__(self, name, value=None, filename=None, filetype=None,83- filesize=None, fileobj=None, cb=None):84- self.name = Header(name).encode()85- self.value = _strify(value)86- if filename is None:87- self.filename = None88- else:89- if isinstance(filename, unicode):90- # Encode with XML entities91- self.filename = filename.encode("ascii", "xmlcharrefreplace")92- else:93- self.filename = str(filename)94- self.filename = self.filename.encode("string_escape").\95- replace('"', '\\"')96- self.filetype = _strify(filetype)97-98- self.filesize = filesize99- self.fileobj = fileobj100- self.cb = cb101-102- if self.value is not None and self.fileobj is not None:103- raise ValueError("Only one of value or fileobj may be specified")104-105- if fileobj is not None and filesize is None:106- # Try and determine the file size107- try:108- self.filesize = os.fstat(fileobj.fileno()).st_size109- except (OSError, AttributeError):110- try:111- fileobj.seek(0, 2)112- self.filesize = fileobj.tell()113- fileobj.seek(0)114- except:115- raise ValueError("Could not determine filesize")116-117- def __cmp__(self, other):118- attrs = ['name', 'value', 'filename', 'filetype', 'filesize', 'fileobj']119- myattrs = [getattr(self, a) for a in attrs]120- oattrs = [getattr(other, a) for a in attrs]121- return cmp(myattrs, oattrs)122-123- def reset(self):124- if self.fileobj is not None:125- self.fileobj.seek(0)126- elif self.value is None:127- raise ValueError("Don't know how to reset this parameter")128-129- @classmethod130- def from_file(cls, paramname, filename):131- """Returns a new MultipartParam object constructed from the local132- file at ``filename``.133-134- ``filesize`` is determined by os.path.getsize(``filename``)135-136- ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]137-138- ``filename`` is set to os.path.basename(``filename``)139- """140-141- return cls(paramname, filename=os.path.basename(filename),142- filetype=mimetypes.guess_type(filename)[0],143- filesize=os.path.getsize(filename),144- fileobj=open(filename, "rb"))145-146- @classmethod147- def from_params(cls, params):148- """Returns a list of MultipartParam objects from a sequence of149- name, value pairs, MultipartParam instances,150- or from a mapping of names to values151-152- The values may be strings or file objects, or MultipartParam objects.153- MultipartParam object names must match the given names in the154- name,value pairs or mapping, if applicable."""155- if hasattr(params, 'items'):156- params = params.items()157-158- retval = []159- for item in params:160- if isinstance(item, cls):161- retval.append(item)162- continue163- name, value = item164- if isinstance(value, cls):165- assert value.name == name166- retval.append(value)167- continue168- if hasattr(value, 'read'):169- # Looks like a file object170- filename = getattr(value, 'name', None)171- if filename is not None:172- filetype = mimetypes.guess_type(filename)[0]173- else:174- filetype = None175-176- retval.append(cls(name=name, filename=filename,177- filetype=filetype, fileobj=value))178- else:179- retval.append(cls(name, value))180- return retval181-182- def encode_hdr(self, boundary):183- """Returns the header of the encoding of this parameter"""184- boundary = encode_and_quote(boundary)185-186- headers = ["--%s" % boundary]187-188- if self.filename:189- disposition = 'form-data; name="%s"; filename="%s"' % (self.name,190- self.filename)191- else:192- disposition = 'form-data; name="%s"' % self.name193-194- headers.append("Content-Disposition: %s" % disposition)195-196- if self.filetype:197- filetype = self.filetype198- else:199- filetype = "text/plain; charset=utf-8"200-201- headers.append("Content-Type: %s" % filetype)202-203- headers.append("")204- headers.append("")205-206- return "\r\n".join(headers)207-208- def encode(self, boundary):209- """Returns the string encoding of this parameter"""210- if self.value is None:211- value = self.fileobj.read()212- else:213- value = self.value214-215- if re.search("^--%s$" % re.escape(boundary), value, re.M):216- raise ValueError("boundary found in encoded string")217-218- return "%s%s\r\n" % (self.encode_hdr(boundary), value)219-220- def iter_encode(self, boundary, blocksize=4096):221- """Yields the encoding of this parameter222- If self.fileobj is set, then blocks of ``blocksize`` bytes are read and223- yielded."""224- total = self.get_size(boundary)225- current = 0226- if self.value is not None:227- block = self.encode(boundary)228- current += len(block)229- yield block230- if self.cb:231- self.cb(self, current, total)232- else:233- block = self.encode_hdr(boundary)234- current += len(block)235- yield block236- if self.cb:237- self.cb(self, current, total)238- last_block = ""239- encoded_boundary = "--%s" % encode_and_quote(boundary)240- boundary_exp = re.compile("^%s$" % re.escape(encoded_boundary),241- re.M)242- while True:243- block = self.fileobj.read(blocksize)244- if not block:245- current += 2246- yield "\r\n"247- if self.cb:248- self.cb(self, current, total)249- break250- last_block += block251- if boundary_exp.search(last_block):252- raise ValueError("boundary found in file data")253- last_block = last_block[-len(encoded_boundary)-2:]254- current += len(block)255- yield block256- if self.cb:257- self.cb(self, current, total)258-259- def get_size(self, boundary):260- """Returns the size in bytes that this param will be when encoded261- with the given boundary."""262- if self.filesize is not None:263- valuesize = self.filesize264- else:265- valuesize = len(self.value)266-267- return len(self.encode_hdr(boundary)) + 2 + valuesize268-269-def encode_string(boundary, name, value):270- """Returns ``name`` and ``value`` encoded as a multipart/form-data271- variable. ``boundary`` is the boundary string used throughout272- a single request to separate variables."""273-274- return MultipartParam(name, value).encode(boundary)275-276-def encode_file_header(boundary, paramname, filesize, filename=None,277- filetype=None):278- """Returns the leading data for a multipart/form-data field that contains279- file data.280-281- ``boundary`` is the boundary string used throughout a single request to282- separate variables.283-284- ``paramname`` is the name of the variable in this request.285-286- ``filesize`` is the size of the file data.287-288- ``filename`` if specified is the filename to give to this field. This289- field is only useful to the server for determining the original filename.290-291- ``filetype`` if specified is the MIME type of this file.292-293- The actual file data should be sent after this header has been sent.294- """295-296- return MultipartParam(paramname, filesize=filesize, filename=filename,297- filetype=filetype).encode_hdr(boundary)298-299-def get_body_size(params, boundary):300- """Returns the number of bytes that the multipart/form-data encoding301- of ``params`` will be."""302- size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))303- return size + len(boundary) + 6304-305-def get_headers(params, boundary):306- """Returns a dictionary with Content-Type and Content-Length headers307- for the multipart/form-data encoding of ``params``."""308- headers = {}309- boundary = urllib.quote_plus(boundary)310- headers['Content-Type'] = "multipart/form-data; boundary=%s" % boundary311- headers['Content-Length'] = str(get_body_size(params, boundary))312- return headers313-314-class multipart_yielder:315- def __init__(self, params, boundary, cb):316- self.params = params317- self.boundary = boundary318- self.cb = cb319-320- self.i = 0321- self.p = None322- self.param_iter = None323- self.current = 0324- self.total = get_body_size(params, boundary)325-326- def __iter__(self):327- return self328-329- def next(self):330- """generator function to yield multipart/form-data representation331- of parameters"""332- if self.param_iter is not None:333- try:334- block = self.param_iter.next()335- self.current += len(block)336- if self.cb:337- self.cb(self.p, self.current, self.total)338- return block339- except StopIteration:340- self.p = None341- self.param_iter = None342-343- if self.i is None:344- raise StopIteration345- elif self.i >= len(self.params):346- self.param_iter = None347- self.p = None348- self.i = None349- block = "--%s--\r\n" % self.boundary350- self.current += len(block)351- if self.cb:352- self.cb(self.p, self.current, self.total)353- return block354-355- self.p = self.params[self.i]356- self.param_iter = self.p.iter_encode(self.boundary)357- self.i += 1358- return self.next()359-360- def reset(self):361- self.i = 0362- self.current = 0363- for param in self.params:364- param.reset()365-366-def multipart_encode(params, boundary=None, cb=None):367- """Encode ``params`` as multipart/form-data.368-369- ``params`` should be a sequence of (name, value) pairs or MultipartParam370- objects, or a mapping of names to values.371- Values are either strings parameter values, or file-like objects to use as372- the parameter value. The file-like objects must support .read() and either373- .fileno() or both .seek() and .tell().374-375- If ``boundary`` is set, then it as used as the MIME boundary. Otherwise376- a randomly generated boundary will be used. In either case, if the377- boundary string appears in the parameter values a ValueError will be378- raised.379-380- If ``cb`` is set, it should be a callback which will get called as blocks381- of data are encoded. It will be called with (param, current, total),382- indicating the current parameter being encoded, the current amount encoded,383- and the total amount to encode.384-385- Returns a tuple of `datagen`, `headers`, where `datagen` is a386- generator that will yield blocks of data that make up the encoded387- parameters, and `headers` is a dictionary with the assoicated388- Content-Type and Content-Length headers.389-390- Examples:391-392- >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )393- >>> s = "".join(datagen)394- >>> assert "value2" in s and "value1" in s395-396- >>> p = MultipartParam("key", "value2")397- >>> datagen, headers = multipart_encode( [("key", "value1"), p] )398- >>> s = "".join(datagen)399- >>> assert "value2" in s and "value1" in s400-401- >>> datagen, headers = multipart_encode( {"key": "value1"} )402- >>> s = "".join(datagen)403- >>> assert "value2" not in s and "value1" in s404-405- """406- if boundary is None:407- boundary = gen_boundary()408- else:409- boundary = urllib.quote_plus(boundary)410-411- headers = get_headers(params, boundary)412- params = MultipartParam.from_params(params)413-414- return multipart_yielder(params, boundary, cb), headersdeleted:requests/packages/poster/streaminghttp.py-199 removed
1-"""Streaming HTTP uploads module.2-3-This module extends the standard httplib and urllib2 objects so that4-iterable objects can be used in the body of HTTP requests.5-6-In most cases all one should have to do is call :func:`register_openers()`7-to register the new streaming http handlers which will take priority over8-the default handlers, and then you can use iterable objects in the body9-of HTTP requests.10-11-**N.B.** You must specify a Content-Length header if using an iterable object12-since there is no way to determine in advance the total size that will be13-yielded, and there is no way to reset an interator.14-15-Example usage:16-17->>> from StringIO import StringIO18->>> import urllib2, poster.streaminghttp19-20->>> opener = poster.streaminghttp.register_openers()21-22->>> s = "Test file data"23->>> f = StringIO(s)24-25->>> req = urllib2.Request("http://localhost:5000", f,26-... {'Content-Length': str(len(s))})27-"""28-29-import httplib, urllib2, socket30-from httplib import NotConnected31-32-__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',33- 'StreamingHTTPHandler', 'register_openers']34-35-if hasattr(httplib, 'HTTPS'):36- __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])37-38-class _StreamingHTTPMixin:39- """Mixin class for HTTP and HTTPS connections that implements a streaming40- send method."""41- def send(self, value):42- """Send ``value`` to the server.43-44- ``value`` can be a string object, a file-like object that supports45- a .read() method, or an iterable object that supports a .next()46- method.47- """48- # Based on python 2.6's httplib.HTTPConnection.send()49- if self.sock is None:50- if self.auto_open:51- self.connect()52- else:53- raise NotConnected()54-55- # send the data to the server. if we get a broken pipe, then close56- # the socket. we want to reconnect when somebody tries to send again.57- #58- # NOTE: we DO propagate the error, though, because we cannot simply59- # ignore the error... the caller will know if they can retry.60- if self.debuglevel > 0:61- print "send:", repr(value)62- try:63- blocksize = 819264- if hasattr(value, 'read') :65- if hasattr(value, 'seek'):66- value.seek(0)67- if self.debuglevel > 0:68- print "sendIng a read()able"69- data = value.read(blocksize)70- while data:71- self.sock.sendall(data)72- data = value.read(blocksize)73- elif hasattr(value, 'next'):74- if hasattr(value, 'reset'):75- value.reset()76- if self.debuglevel > 0:77- print "sendIng an iterable"78- for data in value:79- self.sock.sendall(data)80- else:81- self.sock.sendall(value)82- except socket.error, v:83- if v[0] == 32: # Broken pipe84- self.close()85- raise86-87-class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):88- """Subclass of `httplib.HTTPConnection` that overrides the `send()` method89- to support iterable body objects"""90-91-class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):92- """Subclass of `urllib2.HTTPRedirectHandler` that overrides the93- `redirect_request` method to properly handle redirected POST requests94-95- This class is required because python 2.5's HTTPRedirectHandler does96- not remove the Content-Type or Content-Length headers when requesting97- the new resource, but the body of the original request is not preserved.98- """99-100- handler_order = urllib2.HTTPRedirectHandler.handler_order - 1101-102- # From python2.6 urllib2's HTTPRedirectHandler103- def redirect_request(self, req, fp, code, msg, headers, newurl):104- """Return a Request or None in response to a redirect.105-106- This is called by the http_error_30x methods when a107- redirection response is received. If a redirection should108- take place, return a new Request to allow http_error_30x to109- perform the redirect. Otherwise, raise HTTPError if no-one110- else should try to handle this url. Return None if you can't111- but another Handler might.112- """113- m = req.get_method()114- if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")115- or code in (301, 302, 303) and m == "POST"):116- # Strictly (according to RFC 2616), 301 or 302 in response117- # to a POST MUST NOT cause a redirection without confirmation118- # from the user (of urllib2, in this case). In practice,119- # essentially all clients do redirect in this case, so we120- # do the same.121- # be conciliant with URIs containing a space122- newurl = newurl.replace(' ', '%20')123- newheaders = dict((k, v) for k, v in req.headers.items()124- if k.lower() not in (125- "content-length", "content-type")126- )127- return urllib2.Request(newurl,128- headers=newheaders,129- origin_req_host=req.get_origin_req_host(),130- unverifiable=True)131- else:132- raise urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)133-134-class StreamingHTTPHandler(urllib2.HTTPHandler):135- """Subclass of `urllib2.HTTPHandler` that uses136- StreamingHTTPConnection as its http connection class."""137-138- handler_order = urllib2.HTTPHandler.handler_order - 1139-140- def http_open(self, req):141- """Open a StreamingHTTPConnection for the given request"""142- return self.do_open(StreamingHTTPConnection, req)143-144- def http_request(self, req):145- """Handle a HTTP request. Make sure that Content-Length is specified146- if we're using an interable value"""147- # Make sure that if we're using an iterable object as the request148- # body, that we've also specified Content-Length149- if req.has_data():150- data = req.get_data()151- if hasattr(data, 'read') or hasattr(data, 'next'):152- if not req.has_header('Content-length'):153- raise ValueError(154- "No Content-Length specified for iterable body")155- return urllib2.HTTPHandler.do_request_(self, req)156-157-if hasattr(httplib, 'HTTPS'):158- class StreamingHTTPSConnection(_StreamingHTTPMixin,159- httplib.HTTPSConnection):160- """Subclass of `httplib.HTTSConnection` that overrides the `send()`161- method to support iterable body objects"""162-163- class StreamingHTTPSHandler(urllib2.HTTPSHandler):164- """Subclass of `urllib2.HTTPSHandler` that uses165- StreamingHTTPSConnection as its http connection class."""166-167- handler_order = urllib2.HTTPSHandler.handler_order - 1168-169- def https_open(self, req):170- return self.do_open(StreamingHTTPSConnection, req)171-172- def https_request(self, req):173- # Make sure that if we're using an iterable object as the request174- # body, that we've also specified Content-Length175- if req.has_data():176- data = req.get_data()177- if hasattr(data, 'read') or hasattr(data, 'next'):178- if not req.has_header('Content-length'):179- raise ValueError(180- "No Content-Length specified for iterable body")181- return urllib2.HTTPSHandler.do_request_(self, req)182-183-184-def get_handlers():185- handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186- if hasattr(httplib, "HTTPS"):187- handlers.append(StreamingHTTPSHandler)188- return handlers189- 190-def register_openers():191- """Register the streaming http handlers in the global urllib2 default192- opener object.193-194- Returns the created OpenerDirector object."""195- opener = urllib2.build_opener(*get_handlers())196-197- urllib2.install_opener(opener)198-199- return openeradded:requests/packages/urllib3/contrib/__init__.py
added:requests/packages/urllib3/contrib/ntlmpool.py+117 added
1+# urllib3/contrib/ntlmpool.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+"""8+NTLM authenticating pool, contributed by erikcederstran9+10+Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011+"""12+13+import httplib14+from logging import getLogger15+from ntlm import ntlm16+17+from urllib3 import HTTPSConnectionPool18+19+20+log = getLogger(__name__)21+22+23+class NTLMConnectionPool(HTTPSConnectionPool):24+ """25+ Implements an NTLM authentication version of an urllib3 connection pool26+ """27+28+ scheme = 'https'29+30+ def __init__(self, user, pw, authurl, *args, **kwargs):31+ """32+ authurl is a random URL on the server that is protected by NTLM.33+ user is the Windows user, probably in the DOMAIN\username format.34+ pw is the password for the user.35+ """36+ super(NTLMConnectionPool, self).__init__(*args, **kwargs)37+ self.authurl = authurl38+ self.rawuser = user39+ user_parts = user.split('\\', 1)40+ self.domain = user_parts[0].upper()41+ self.user = user_parts[1]42+ self.pw = pw43+44+ def _new_conn(self):45+ # Performs the NTLM handshake that secures the connection. The socket46+ # must be kept open while requests are performed.47+ self.num_connections += 148+ log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' %49+ (self.num_connections, self.host, self.authurl))50+51+ headers = {}52+ headers['Connection'] = 'Keep-Alive'53+ req_header = 'Authorization'54+ resp_header = 'www-authenticate'55+56+ conn = httplib.HTTPSConnection(host=self.host, port=self.port)57+58+ # Send negotiation message59+ headers[req_header] = (60+ 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))61+ log.debug('Request headers: %s' % headers)62+ conn.request('GET', self.authurl, None, headers)63+ res = conn.getresponse()64+ reshdr = dict(res.getheaders())65+ log.debug('Response status: %s %s' % (res.status, res.reason))66+ log.debug('Response headers: %s' % reshdr)67+ log.debug('Response data: %s [...]' % res.read(100))68+69+ # Remove the reference to the socket, so that it can not be closed by70+ # the response object (we want to keep the socket open)71+ res.fp = None72+73+ # Server should respond with a challenge message74+ auth_header_values = reshdr[resp_header].split(', ')75+ auth_header_value = None76+ for s in auth_header_values:77+ if s[:5] == 'NTLM ':78+ auth_header_value = s[5:]79+ if auth_header_value is None:80+ raise Exception('Unexpected %s response header: %s' %81+ (resp_header, reshdr[resp_header]))82+83+ # Send authentication message84+ ServerChallenge, NegotiateFlags = \85+ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)86+ auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,87+ self.user,88+ self.domain,89+ self.pw,90+ NegotiateFlags)91+ headers[req_header] = 'NTLM %s' % auth_msg92+ log.debug('Request headers: %s' % headers)93+ conn.request('GET', self.authurl, None, headers)94+ res = conn.getresponse()95+ log.debug('Response status: %s %s' % (res.status, res.reason))96+ log.debug('Response headers: %s' % dict(res.getheaders()))97+ log.debug('Response data: %s [...]' % res.read()[:100])98+ if res.status != 200:99+ if res.status == 401:100+ raise Exception('Server rejected request: wrong '101+ 'username or password')102+ raise Exception('Wrong server response: %s %s' %103+ (res.status, res.reason))104+105+ res.fp = None106+ log.debug('Connection established')107+ return conn108+109+ def urlopen(self, method, url, body=None, headers=None, retries=3,110+ redirect=True, assert_same_host=True):111+ if headers is None:112+ headers = {}113+ headers['Connection'] = 'Keep-Alive'114+ return super(NTLMConnectionPool, self).urlopen(method, url, body,115+ headers, retries,116+ redirect,117+ assert_same_host)added:requests/packages/urllib3/__init__.py+32 added
1+# urllib3/__init__.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+"""8+urllib3 - Thread-safe connection pooling and re-using.9+"""10+11+__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"12+__license__ = "MIT"13+__version__ = "$Rev$"14+15+16+from .connectionpool import (17+ HTTPConnectionPool,18+ HTTPSConnectionPool,19+ connection_from_url,20+ get_host,21+ make_headers)22+23+24+from .exceptions import (25+ HTTPError,26+ MaxRetryError,27+ SSLError,28+ TimeoutError)29+30+from .poolmanager import PoolManager31+from .response import HTTPResponse32+from .filepost import encode_multipart_formdataadded:requests/packages/urllib3/_collections.py+121 added
1+# urllib3/_collections.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+from collections import MutableMapping, deque8+9+10+__all__ = ['RecentlyUsedContainer']11+12+13+class AccessEntry(object):14+ __slots__ = ('key', 'is_valid')15+16+ def __init__(self, key, is_valid=True):17+ self.key = key18+ self.is_valid = is_valid19+20+21+class RecentlyUsedContainer(MutableMapping):22+ """23+ Provides a dict-like that maintains up to ``maxsize`` keys while throwing24+ away the least-recently-used keys beyond ``maxsize``.25+ """26+27+ # TODO: Make this threadsafe. _prune_invalidated_entries should be the28+ # only real pain-point for this.29+30+ # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we31+ # will attempt to cleanup the invalidated entries in the access_log32+ # datastructure during the next 'get' operation.33+ CLEANUP_FACTOR = 1034+35+ def __init__(self, maxsize=10):36+ self._maxsize = maxsize37+38+ self._container = {}39+40+ # We use a deque to to store our keys ordered by the last access.41+ self.access_log = deque()42+43+ # We look up the access log entry by the key to invalidate it so we can44+ # insert a new authorative entry at the head without having to dig and45+ # find the old entry for removal immediately.46+ self.access_lookup = {}47+48+ # Trigger a heap cleanup when we get past this size49+ self.access_log_limit = maxsize * self.CLEANUP_FACTOR50+51+ def _push_entry(self, key):52+ "Push entry onto our access log, invalidate the old entry if exists."53+ # Invalidate old entry if it exists54+ old_entry = self.access_lookup.get(key)55+ if old_entry:56+ old_entry.is_valid = False57+58+ new_entry = AccessEntry(key)59+60+ self.access_lookup[key] = new_entry61+ self.access_log.appendleft(new_entry)62+63+ def _prune_entries(self, num):64+ "Pop entries from our access log until we popped ``num`` valid ones."65+ while num > 0:66+ p = self.access_log.pop()67+68+ if not p.is_valid:69+ continue # Invalidated entry, skip70+71+ del self._container[p.key]72+ del self.access_lookup[p.key]73+ num -= 174+75+ def _prune_invalidated_entries(self):76+ "Rebuild our access_log without the invalidated entries."77+ self.access_log = deque(e for e in self.access_log if e.is_valid)78+79+ def _get_ordered_access_keys(self):80+ # Used for testing81+ return [e.key for e in self.access_log if e.is_valid]82+83+ def __getitem__(self, key):84+ item = self._container.get(key)85+86+ if not item:87+ return88+89+ # Insert new entry with new high priority, also implicitly invalidates90+ # the old entry.91+ self._push_entry(key)92+93+ if len(self.access_log) > self.access_log_limit:94+ # Heap is getting too big, try to clean up any tailing invalidated95+ # entries.96+ self._prune_invalidated_entries()97+98+ return item99+100+ def __setitem__(self, key, item):101+ # Add item to our container and access log102+ self._container[key] = item103+ self._push_entry(key)104+105+ # Discard invalid and excess entries106+ self._prune_entries(len(self._container) - self._maxsize)107+108+109+ def __delitem__(self, key):110+ self._invalidate_entry(key)111+ del self._container[key]112+ del self._access_lookup[key]113+114+ def __len__(self):115+ return len(self.access_log)116+117+ def __iter__(self):118+ return self._container.__iter__()119+120+ def __contains__(self, key):121+ return self._container.__contains__(key)added:requests/packages/urllib3/connectionpool.py+531 added
1+# urllib3/connectionpool.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+import logging8+import socket9+10+11+from urllib import urlencode12+from httplib import HTTPConnection, HTTPSConnection, HTTPException13+from Queue import Queue, Empty, Full14+from select import select15+from socket import error as SocketError, timeout as SocketTimeout16+17+18+try:19+ import ssl20+ BaseSSLError = ssl.SSLError21+except ImportError:22+ ssl = None23+ BaseSSLError = None24+25+26+from .filepost import encode_multipart_formdata27+from .response import HTTPResponse28+from .exceptions import (29+ SSLError,30+ MaxRetryError,31+ TimeoutError,32+ HostChangedError,33+ EmptyPoolError)34+35+36+log = logging.getLogger(__name__)37+38+_Default = object()39+40+41+## Connection objects (extension of httplib)42+43+class VerifiedHTTPSConnection(HTTPSConnection):44+ """45+ Based on httplib.HTTPSConnection but wraps the socket with46+ SSL certification.47+ """48+49+ def __init__(self, **kwargs):50+ HTTPSConnection.__init__(self, **kwargs)51+ self.cert_reqs = None52+ self.ca_certs = None53+54+ def set_cert(self, key_file=None, cert_file=None,55+ cert_reqs='CERT_NONE', ca_certs=None):56+ ssl_req_scheme = {57+ 'CERT_NONE': ssl.CERT_NONE,58+ 'CERT_OPTIONAL': ssl.CERT_OPTIONAL,59+ 'CERT_REQUIRED': ssl.CERT_REQUIRED60+ }61+62+ self.key_file = key_file63+ self.cert_file = cert_file64+ self.cert_reqs = ssl_req_scheme.get(cert_reqs) or ssl.CERT_NONE65+ self.ca_certs = ca_certs66+67+ def connect(self):68+ # Add certificate verification69+ sock = socket.create_connection((self.host, self.port), self.timeout)70+71+ # Wrap socket using verification with the root certs in72+ # trusted_root_certs73+ self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file,74+ cert_reqs=self.cert_reqs,75+ ca_certs=self.ca_certs)76+77+78+## Pool objects79+80+class ConnectionPool(object):81+ pass82+83+84+class HTTPConnectionPool(ConnectionPool):85+ """86+ Thread-safe connection pool for one host.87+88+ host89+ Host used for this HTTP Connection (e.g. "localhost"), passed into90+ httplib.HTTPConnection()91+92+ port93+ Port used for this HTTP Connection (None is equivalent to 80), passed94+ into httplib.HTTPConnection()95+96+ strict97+ Causes BadStatusLine to be raised if the status line can't be parsed98+ as a valid HTTP/1.0 or 1.1 status line, passed into99+ httplib.HTTPConnection()100+101+ timeout102+ Socket timeout for each individual connection, can be a float. None103+ disables timeout.104+105+ maxsize106+ Number of connections to save that can be reused. More than 1 is useful107+ in multithreaded situations. If ``block`` is set to false, more108+ connections will be created but they will not be saved once they've109+ been used.110+111+ block112+ If set to True, no more than ``maxsize`` connections will be used at113+ a time. When no free connections are available, the call will block114+ until a connection has been released. This is a useful side effect for115+ particular multithreaded situations where one does not want to use more116+ than maxsize connections per host to prevent flooding.117+118+ headers119+ Headers to include with all requests, unless other headers are given120+ explicitly.121+ """122+123+ scheme = 'http'124+125+ def __init__(self, host, port=None, strict=False, timeout=None, maxsize=1,126+ block=False, headers=None):127+ self.host = host128+ self.port = port129+ self.strict = strict130+ self.timeout = timeout131+ self.pool = Queue(maxsize)132+ self.block = block133+ self.headers = headers or {}134+135+ # Fill the queue up so that doing get() on it will block properly136+ for _ in xrange(maxsize):137+ self.pool.put(None)138+139+ # These are mostly for testing and debugging purposes.140+ self.num_connections = 0141+ self.num_requests = 0142+143+ def _new_conn(self):144+ """145+ Return a fresh HTTPConnection.146+ """147+ self.num_connections += 1148+ log.info("Starting new HTTP connection (%d): %s" %149+ (self.num_connections, self.host))150+ return HTTPConnection(host=self.host, port=self.port)151+152+ def _get_conn(self, timeout=None):153+ """154+ Get a connection. Will return a pooled connection if one is available.155+ Otherwise, a fresh connection is returned.156+ """157+ conn = None158+ try:159+ conn = self.pool.get(block=self.block, timeout=timeout)160+161+ # If this is a persistent connection, check if it got disconnected162+ if conn and conn.sock and select([conn.sock], [], [], 0.0)[0]:163+ # Either data is buffered (bad), or the connection is dropped.164+ log.info("Resetting dropped connection: %s" % self.host)165+ conn.close()166+167+ except Empty:168+ if self.block:169+ raise EmptyPoolError("Pool reached maximum size and no more "170+ "connections are allowed.")171+ pass # Oh well, we'll create a new connection then172+173+ return conn or self._new_conn()174+175+ def _put_conn(self, conn):176+ """177+ Put a connection back into the pool.178+ If the pool is already full, the connection is discarded because we179+ exceeded maxsize. If connections are discarded frequently, then maxsize180+ should be increased.181+ """182+ try:183+ self.pool.put(conn, block=False)184+ except Full:185+ # This should never happen if self.block == True186+ log.warning("HttpConnectionPool is full, discarding connection: %s"187+ % self.host)188+189+ def _make_request(self, conn, method, url, timeout=_Default,190+ **httplib_request_kw):191+ """192+ Perform a request on a given httplib connection object taken from our193+ pool.194+ """195+ self.num_requests += 1196+197+ if timeout is _Default:198+ timeout = self.timeout199+200+201+ conn.request(method, url, **httplib_request_kw)202+ conn.sock.settimeout(timeout)203+ httplib_response = conn.getresponse()204+205+206+ log.debug("\"%s %s %s\" %s %s" %207+ (method, url,208+ conn._http_vsn_str, # pylint: disable-msg=W0212209+ httplib_response.status, httplib_response.length))210+211+ return httplib_response212+213+214+ def is_same_host(self, url):215+ return (url.startswith('/') or216+ get_host(url) == (self.scheme, self.host, self.port))217+218+ def urlopen(self, method, url, body=None, headers=None, retries=3,219+ redirect=True, assert_same_host=True, timeout=_Default,220+ pool_timeout=None, release_conn=None, **response_kw):221+ """222+ Get a connection from the pool and perform an HTTP request.223+224+ method225+ HTTP request method (such as GET, POST, PUT, etc.)226+227+ body228+ Data to send in the request body (useful for creating229+ POST requests, see HTTPConnectionPool.post_url for230+ more convenience).231+232+ headers233+ Dictionary of custom headers to send, such as User-Agent,234+ If-None-Match, etc. If None, pool headers are used. If provided,235+ these headers completely replace any pool-specific headers.236+237+ retries238+ Number of retries to allow before raising239+ a MaxRetryError exception.240+241+ redirect242+ Automatically handle redirects (status codes 301, 302, 303, 307),243+ each redirect counts as a retry.244+245+ assert_same_host246+ If True, will make sure that the host of the pool requests is247+ consistent else will raise HostChangedError. When False, you can248+ use the pool on an HTTP proxy and request foreign hosts.249+250+ timeout251+ If specified, overrides the default timeout for this one request.252+253+ pool_timeout254+ If set and the pool is set to block=True, then this method will255+ block for ``pool_timeout`` seconds and raise EmptyPoolError if no256+ connection is available within the time period.257+258+ release_conn259+ If False, then the urlopen call will not release the connection260+ back into the pool once a response is received. This is useful if261+ you're not preloading the response's content immediately. You will262+ need to call ``r.release_conn()`` on the response ``r`` to return263+ the connection back into the pool. If None, it takes the value of264+ ``response_kw.get('preload_content', True)``.265+266+ Additional parameters are passed to267+ ``HTTPResponse.from_httplib(r, **response_kw)``268+ """269+ if headers is None:270+ headers = self.headers271+272+ if retries < 0:273+ raise MaxRetryError("Max retries exceeded for url: %s" % url)274+275+ if release_conn is None:276+ release_conn = response_kw.get('preload_content', True)277+278+ # Check host279+ if assert_same_host and not self.is_same_host(url):280+ host = "%s://%s" % (self.scheme, self.host)281+ if self.port:282+ host = "%s:%d" % (host, self.port)283+284+ raise HostChangedError("Connection pool with host '%s' tried to "285+ "open a foreign host: %s" % (host, url))286+287+ conn = None288+289+ try:290+ # Request a connection from the queue291+ # (Could raise SocketError: Bad file descriptor)292+ conn = self._get_conn(timeout=pool_timeout)293+ # Make the request on the httplib connection object294+ httplib_response = self._make_request(conn, method, url,295+ timeout=timeout,296+ body=body, headers=headers)297+ # print '!'298+299+ # Import httplib's response into our own wrapper object300+ response = HTTPResponse.from_httplib(httplib_response,301+ pool=self,302+ connection=conn,303+ **response_kw)304+305+ if release_conn:306+ # The connection will be released manually in the ``finally:``307+ response.connection = None308+309+ # else:310+ # The connection will be put back into the pool when311+ # ``response.release_conn()`` is called (implicitly by312+ # ``response.read()``)313+314+ except (SocketTimeout, Empty), e:315+ # Timed out either by socket or queue316+ raise TimeoutError("Request timed out after %f seconds" %317+ self.timeout)318+319+ except (BaseSSLError), e:320+ # SSL certificate error321+ raise SSLError(e)322+323+ except (HTTPException, SocketError), e:324+ # Connection broken, discard. It will be replaced next _get_conn().325+ conn = None326+327+ finally:328+ if conn and release_conn:329+ # Put the connection back to be reused330+ self._put_conn(conn)331+332+ if not conn:333+ log.warn("Retrying (%d attempts remain) after connection "334+ "broken by '%r': %s" % (retries, e, url))335+ return self.urlopen(method, url, body, headers, retries - 1,336+ redirect, assert_same_host) # Try again337+338+ # Handle redirection339+ if (redirect and340+ response.status in [301, 302, 303, 307] and341+ 'location' in response.headers): # Redirect, retry342+ log.info("Redirecting %s -> %s" %343+ (url, response.headers.get('location')))344+ return self.urlopen(method, response.headers.get('location'), body,345+ headers, retries - 1, redirect,346+ assert_same_host)347+348+ return response349+350+ def get_url(self, url, fields=None, headers=None, retries=3,351+ redirect=True, **response_kw):352+ """353+ Wrapper for performing GET with urlopen (see urlopen for more details).354+355+ Supports an optional ``fields`` dictionary parameter key/value strings.356+ If provided, they will be added to the url.357+ """358+ if fields:359+ url += '?' + urlencode(fields)360+ return self.urlopen('GET', url, headers=headers, retries=retries,361+ redirect=redirect, **response_kw)362+363+ def post_url(self, url, fields=None, headers=None, retries=3,364+ redirect=True, encode_multipart=True, multipart_boundary=None,365+ **response_kw):366+ """367+ Wrapper for performing POST with urlopen (see urlopen368+ for more details).369+370+ Supports an optional ``fields`` parameter of key/value strings AND371+ key/filetuple. A filetuple is a (filename, data) tuple. For example:372+373+ fields = {374+ 'foo': 'bar',375+ 'foofile': ('foofile.txt', 'contents of foofile'),376+ }377+378+ If encode_multipart=True (default), then379+ ``urllib3.filepost.encode_multipart_formdata`` is used to encode the380+ payload with the appropriate content type. Otherwise381+ ``urllib.urlencode`` is used with 'application/x-www-form-urlencoded'382+ content type.383+384+ Multipart encoding must be used when posting files, and it's reasonably385+ safe to use it other times too. It may break request signing, such as386+ OAuth.387+388+ NOTE: If ``headers`` are supplied, the 'Content-Type' value will be389+ overwritten because it depends on the dynamic random boundary string390+ which is used to compose the body of the request.391+ """392+ if encode_multipart:393+ body, content_type = encode_multipart_formdata(fields or {},394+ boundary=multipart_boundary)395+ else:396+ body, content_type = (397+ urlencode(fields or {}),398+ 'application/x-www-form-urlencoded')399+400+ headers = headers or {}401+ headers.update({'Content-Type': content_type})402+403+ return self.urlopen('POST', url, body, headers=headers,404+ retries=retries, redirect=redirect, **response_kw)405+406+407+class HTTPSConnectionPool(HTTPConnectionPool):408+ """409+ Same as HTTPConnectionPool, but HTTPS.410+ """411+412+ scheme = 'https'413+414+ def __init__(self, host, port=None,415+ strict=False, timeout=None, maxsize=1,416+ block=False, headers=None,417+ key_file=None, cert_file=None,418+ cert_reqs=ssl.CERT_REQUIRED, ca_certs=None):419+420+ super(HTTPSConnectionPool, self).__init__(host, port,421+ strict, timeout, maxsize,422+ block, headers)423+ self.key_file = key_file424+ self.cert_file = cert_file425+ self.cert_reqs = cert_reqs426+ self.ca_certs = ca_certs427+428+ def _new_conn(self):429+ """430+ Return a fresh HTTPSConnection.431+ """432+433+ self.num_connections += 1434+ log.info("Starting new HTTPS connection (%d): %s"435+ % (self.num_connections, self.host))436+437+ if not ssl:438+ return HTTPSConnection(host=self.host, port=self.port)439+440+ connection = VerifiedHTTPSConnection(host=self.host, port=self.port)441+ connection.set_cert(key_file=self.key_file, cert_file=self.cert_file,442+ cert_reqs=self.cert_reqs, ca_certs=self.ca_certs)443+ return connection444+445+446+## Helpers447+448+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,449+ basic_auth=None):450+ """451+ Shortcuts for generating request headers.452+453+ keep_alive454+ If true, adds 'connection: keep-alive' header.455+456+ accept_encoding457+ Can be a boolean, list, or string.458+ True translates to 'gzip,deflate'.459+ List will get joined by comma.460+ String will be used as provided.461+462+ user_agent463+ String representing the user-agent you want, such as464+ "python-urllib3/0.6"465+466+ basic_auth467+ Colon-separated username:password string for 'authorization: basic ...'468+ auth header.469+ """470+ headers = {}471+ if accept_encoding:472+ if isinstance(accept_encoding, str):473+ pass474+ elif isinstance(accept_encoding, list):475+ accept_encoding = ','.join(accept_encoding)476+ else:477+ accept_encoding = 'gzip,deflate'478+ headers['accept-encoding'] = accept_encoding479+480+ if user_agent:481+ headers['user-agent'] = user_agent482+483+ if keep_alive:484+ headers['connection'] = 'keep-alive'485+486+ if basic_auth:487+ headers['authorization'] = 'Basic ' + \488+ basic_auth.encode('base64').strip()489+490+ return headers491+492+493+def get_host(url):494+ """495+ Given a url, return its scheme, host and port (None if it's not there).496+497+ For example:498+ >>> get_host('http://google.com/mail/')499+ http, google.com, None500+ >>> get_host('google.com:80')501+ http, google.com, 80502+ """503+ # This code is actually similar to urlparse.urlsplit, but much504+ # simplified for our needs.505+ port = None506+ scheme = 'http'507+ if '//' in url:508+ scheme, url = url.split('://', 1)509+ if '/' in url:510+ url, _path = url.split('/', 1)511+ if ':' in url:512+ url, port = url.split(':', 1)513+ port = int(port)514+ return scheme, url, port515+516+517+def connection_from_url(url, **kw):518+ """519+ Given a url, return an HTTP(S)ConnectionPool instance of its host.520+521+ This is a shortcut for not having to determine the host of the url522+ before creating an HTTP(S)ConnectionPool instance.523+524+ Passes on whatever kw arguments to the constructor of525+ HTTP(S)ConnectionPool. (e.g. timeout, maxsize, block)526+ """527+ scheme, host, port = get_host(url)528+ if scheme == 'https':529+ return HTTPSConnectionPool(host, port=port, **kw)530+ else:531+ return HTTPConnectionPool(host, port=port, **kw)added:requests/packages/urllib3/exceptions.py+35 added
1+# urllib3/exceptions.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+## Exceptions8+9+class HTTPError(Exception):10+ "Base exception used by this module."11+ pass12+13+14+class SSLError(Exception):15+ "Raised when SSL certificate fails in an HTTPS connection."16+ pass17+18+19+class MaxRetryError(HTTPError):20+ "Raised when the maximum number of retries is exceeded."21+ pass22+23+24+class TimeoutError(HTTPError):25+ "Raised when a socket timeout occurs."26+ pass27+28+29+class HostChangedError(HTTPError):30+ "Raised when an existing pool gets a request for a foreign host."31+ pass32+33+class EmptyPoolError(HTTPError):34+ "Raised when a pool runs out of connections and no more are allowed."35+ passadded:requests/packages/urllib3/filepost.py+58 added
1+# urllib3/filepost.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+import codecs8+import mimetools9+import mimetypes10+11+try:12+ from cStringIO import StringIO13+except ImportError:14+ from StringIO import StringIO # pylint: disable-msg=W040415+16+17+writer = codecs.lookup('utf-8')[3]18+19+20+def get_content_type(filename):21+ return mimetypes.guess_type(filename)[0] or 'application/octet-stream'22+23+24+def encode_multipart_formdata(fields, boundary=None):25+ body = StringIO()26+ if boundary is None:27+ boundary = mimetools.choose_boundary()28+29+ for fieldname, value in fields.iteritems():30+ body.write('--%s\r\n' % (boundary))31+32+ if isinstance(value, tuple):33+ filename, data = value34+ writer(body).write('Content-Disposition: form-data; name="%s"; '35+ 'filename="%s"\r\n' % (fieldname, filename))36+ body.write('Content-Type: %s\r\n\r\n' %37+ (get_content_type(filename)))38+ else:39+ data = value40+ writer(body).write('Content-Disposition: form-data; name="%s"\r\n'41+ % (fieldname))42+ body.write('Content-Type: text/plain\r\n\r\n')43+44+ if isinstance(data, int):45+ data = str(data) # Backwards compatibility46+47+ if isinstance(data, unicode):48+ writer(body).write(data)49+ else:50+ body.write(data)51+52+ body.write('\r\n')53+54+ body.write('--%s--\r\n' % (boundary))55+56+ content_type = 'multipart/form-data; boundary=%s' % boundary57+58+ return body.getvalue(), content_typeadded:requests/packages/urllib3/poolmanager.py+79 added
1+# urllib3/poolmanager.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+from ._collections import RecentlyUsedContainer8+from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, get_host9+10+11+pool_classes_by_scheme = {12+ 'http': HTTPConnectionPool,13+ 'https': HTTPSConnectionPool,14+}15+16+port_by_scheme = {17+ 'http': 80,18+ 'https': 443,19+}20+21+22+class PoolManager(object):23+ """24+ Allows for arbitrary requests while transparently keeping track of25+ necessary connection pools for you.26+27+ num_pools28+ Number of connection pools to cache before discarding the least recently29+ used pool.30+31+ Additional parameters are used to create fresh ConnectionPool instances.32+33+ """34+35+ # TODO: Make sure there are no memory leaks here.36+37+ def __init__(self, num_pools=10, **connection_pool_kw):38+ self.connection_pool_kw = connection_pool_kw39+40+ self.pools = RecentlyUsedContainer(num_pools)41+ self.recently_used_pools = []42+43+ def connection_from_host(self, host, port=80, scheme='http'):44+ """45+ Get a ConnectionPool based on the host, port, and scheme.46+ """47+ pool_key = (scheme, host, port)48+49+50+ # If the scheme, host, or port doesn't match existing open connections,51+ # open a new ConnectionPool.52+ pool = self.pools.get(pool_key)53+ if pool:54+ return pool55+56+ # Make a fresh ConnectionPool of the desired type57+ pool_cls = pool_classes_by_scheme[scheme]58+ pool = pool_cls(host, port, **self.connection_pool_kw)59+60+ self.pools[pool_key] = pool61+62+ return pool63+64+ def connection_from_url(self, url):65+ """66+ Similar to connectionpool.connection_from_url but doesn't pass any67+ additional keywords to the ConnectionPool constructor. Additional68+ keywords are taken from the PoolManager constructor.69+ """70+ scheme, host, port = get_host(url)71+72+ port = port or port_by_scheme.get(scheme, 80)73+74+ return self.connection_from_host(host, port=port, scheme=scheme)75+76+ def urlopen(self, method, url, **kw):77+ "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."78+ conn = self.connection_from_url(url)79+ return conn.urlopen(method, url, **kw)added:requests/packages/urllib3/response.py+180 added
1+# urllib3/response.py2+# Copyright 2008-2011 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3+#4+# This module is part of urllib3 and is released under5+# the MIT License: http://www.opensource.org/licenses/mit-license.php6+7+import gzip8+import logging9+import zlib10+11+12+try:13+ from cStringIO import StringIO14+except ImportError:15+ from StringIO import StringIO # pylint: disable-msg=W040416+17+18+from .exceptions import HTTPError19+20+21+log = logging.getLogger(__name__)22+23+24+def decode_gzip(data):25+ gzipper = gzip.GzipFile(fileobj=StringIO(data))26+ return gzipper.read()27+28+29+def decode_deflate(data):30+ try:31+ return zlib.decompress(data)32+ except zlib.error:33+ return zlib.decompress(data, -zlib.MAX_WBITS)34+35+36+class HTTPResponse(object):37+ """38+ HTTP Response container.39+40+ Backwards-compatible to httplib's HTTPResponse but the response ``body`` is41+ loaded and decoded on-demand when the ``data`` property is accessed.42+43+ Extra parameters for behaviour not present in httplib.HTTPResponse:44+45+ preload_content46+ If True, the response's body will be preloaded during construction.47+48+ decode_content49+ If True, attempts to decode specific content-encoding's based on headers50+ (like 'gzip' and 'deflate') will be skipped and raw data will be used51+ instead.52+53+ original_response54+ When this HTTPResponse wrapper is generated from an httplib.HTTPResponse55+ object, it's convenient to include the original for debug purposes. It's56+ otherwise unused.57+ """58+59+ CONTENT_DECODERS = {60+ 'gzip': decode_gzip,61+ 'deflate': decode_deflate,62+ }63+64+ def __init__(self, body='', headers=None, status=0, version=0, reason=None,65+ strict=0, preload_content=True, decode_content=True,66+ original_response=None, pool=None, connection=None):67+ self.headers = headers or {}68+ self.status = status69+ self.version = version70+ self.reason = reason71+ self.strict = strict72+73+ self._decode_content = decode_content74+ self._body = None75+ self._fp = None76+ self._original_response = original_response77+78+ self._pool = pool79+ self._connection = connection80+81+ if hasattr(body, 'read'):82+ self._fp = body83+84+ if preload_content:85+ self._body = self.read(decode_content=decode_content)86+87+ def release_conn(self):88+ if not self._pool or not self._connection:89+ return90+91+ self._pool._put_conn(self._connection)92+ self._connection = None93+94+ @property95+ def data(self):96+ # For backwords-compat with earlier urllib3 0.4 and earlier.97+ if self._body:98+ return self._body99+100+ if self._fp:101+ return self.read(decode_content=self._decode_content,102+ cache_content=True)103+104+ def read(self, amt=None, decode_content=True, cache_content=False):105+ """106+ Similar to ``httplib.HTTPResponse.read(amt=None)``.107+108+ amt109+ How much of the content to read. If specified, decoding and caching110+ is skipped because we can't decode partial content nor does it make111+ sense to cache partial content as the full response.112+113+ decode_content114+ If True, will attempt to decode the body based on the115+ 'content-encoding' header. (Overridden if ``amt`` is set.)116+117+ cache_content118+ If True, will save the returned data such that the same result is119+ returned despite of the state of the underlying file object. This120+ is useful if you want the ``.data`` property to continue working121+ after having ``.read()`` the file object. (Overridden if ``amt`` is122+ set.)123+ """124+ content_encoding = self.headers.get('content-encoding')125+ decoder = self.CONTENT_DECODERS.get(content_encoding)126+127+ data = self._fp and self._fp.read(amt)128+129+ try:130+131+ if amt:132+ return data133+134+ if not decode_content or not decoder:135+ if cache_content:136+ self._body = data137+138+ return data139+140+ try:141+ data = decoder(data)142+ except IOError:143+ raise HTTPError("Received response with content-encoding: %s, but "144+ "failed to decode it." % content_encoding)145+146+ if cache_content:147+ self._body = data148+149+ return data150+151+ finally:152+153+ if self._original_response and self._original_response.isclosed():154+ self.release_conn()155+156+ @staticmethod157+ def from_httplib(r, **response_kw):158+ """159+ Given an httplib.HTTPResponse instance ``r``, return a corresponding160+ urllib3.HTTPResponse object.161+162+ Remaining parameters are passed to the HTTPResponse constructor, along163+ with ``original_response=r``.164+ """165+166+ return HTTPResponse(body=r,167+ headers=dict(r.getheaders()),168+ status=r.status,169+ version=r.version,170+ reason=r.reason,171+ strict=r.strict,172+ original_response=r,173+ **response_kw)174+175+ # Backwards-compatibility methods for httplib.HTTPResponse176+ def getheaders(self):177+ return self.headers178+179+ def getheader(self, name, default=None):180+ return self.headers.get(name, default)modified:requests/packages/__init__.py+1 added-1 removed
1 from __future__ import absolute_import2 3-from . import poster3+from . import urllib3added:requests/_config.py+52 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.config5+~~~~~~~~~~~~~~~6+7+This module provides the Requests configuration defaults.8+9+settings parameters:10+11+- :base_headers: - Sets default User-Agent to `python-requests.org`12+- :accept_gzip: - Whether or not to accept gzip-compressed data13+- :proxies: - http proxies?14+- :verbose: - display verbose information?15+- :timeout: - timeout time until request terminates16+- :max_redirects: - maximum number of allowed redirects?17+- :decode_unicode: - whether or not to accept unicode?18+19+"""20+21+def get_config(config=None, default_config=None):22+ """Merges two given configurations."""23+24+ # Allow raw calls.25+ if config is None:26+ config=dict()27+28+ # Use the module-level defaults, if none is given.29+ if default_config is None:30+ default_config = defaults.copy()31+32+33+ d = default_config.copy()34+ d.update(config)35+36+ return d37+38+39+# Module-level defaults.40+defaults = dict()41+42+defaults['base_headers'] = {'User-Agent': 'python-requests.org'}43+defaults['accept_gzip'] = True44+defaults['proxies'] = {}45+defaults['verbose'] = None46+defaults['timeout'] = None47+defaults['max_redirects'] = 3048+defaults['decode_unicode'] = True49+defaults['keep_alive'] = True50+defaults['max_connections'] = 1051+52+modified:requests/api.py+23 added-12 removed
2 unmodified lines3 """4 requests.api5 ~~~~~~~~~~~~6 7-This module impliments the Requests API.7+This module implements the Requests API.8 9 :copyright: (c) 2011 by Kenneth Reitz.10 :license: ISC, see LICENSE for more details.11 12 """13 14-import config15-from .models import Request, Response, AuthObject14+from ._config import get_config15+from .models import Request, Response16 from .status_codes import codes17 from .hooks import dispatch_hook18 from .utils import cookiejar_from_dict, header_expand19 2 unmodified lines22 23 24 def request(method, url,25 params=None, data=None, headers=None, cookies=None, files=None, auth=None,26- timeout=None, allow_redirects=False, proxies=None, hooks=None):26+ timeout=None, allow_redirects=False, proxies=None, hooks=None,27+ config=None, _pools=None, _return_request=False):28 29 """Constructs and sends a :class:`Request <Request>`.30 Returns :class:`Response <Response>` object.31 7 unmodified lines39 :param auth: (optional) AuthObject to enable Basic HTTP Auth.40 :param timeout: (optional) Float describing the timeout of the request.41 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.42 :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.43+ :param _pools: (optional) An HTTP PoolManager to use.44 """45 46 method = str(method).upper()47+ config = get_config(config)48 49 if cookies is None:50 cookies = {}51 49- cookies = cookiejar_from_dict(cookies)52+ # cookies = cookiejar_from_dict(cookies)53 54 # Expand header values55 if headers:56 for k, v in headers.items() or {}:4 unmodified lines61 url=url,62 data=data,63 params=params,64 headers=headers,62- cookiejar=cookies,65+ cookies=cookies,66 files=files,67 auth=auth,65- timeout=timeout or config.settings.timeout,68+ timeout=timeout or config.get('timeout'),69+ hooks=hooks,70 allow_redirects=allow_redirects,67- proxies=proxies or config.settings.proxies,71+ proxies=proxies or config.get('proxies'),72+ _pools=_pools73 )74 75 # Arguments manipulation hook.76 args = dispatch_hook('args', hooks, args)77 78+ # Create Request object.79 r = Request(**args)80 81 # Pre-request hook.82 r = dispatch_hook('pre_request', hooks, r)83 84+ # Only construct the request (for async)85+ if _return_request:86+ return r87+88 # Send the HTTP Request.89 r.send()90 91+ # TODO: Add these hooks inline.92 # Post-request hook.93 r = dispatch_hook('post_request', hooks, r)94 95 # Response manipulation hook.8 unmodified lines104 :param url: URL for the new :class:`Request` object.105 :param **kwargs: Optional arguments that ``request`` takes.106 """107 97- if "allow_redirects" not in kwargs:98- kwargs["allow_redirects"] = True108+ if 'allow_redirects' not in kwargs:109+ kwargs['allow_redirects'] = True110 111 return request('get', url, **kwargs)112 113 3 unmodified lines117 :param url: URL for the new :class:`Request` object.118 :param **kwargs: Optional arguments that ``request`` takes.119 """120 110- if "allow_redirects" not in kwargs:111- kwargs["allow_redirects"] = True121+ if 'allow_redirects' not in kwargs:122+ kwargs['allow_redirects'] = True123 124 return request('head', url, **kwargs)125 126 41 unmodified linesmodified:requests/async.py+71 added-25 removed
1 # -*- coding: utf-8 -*-2 3 """4- requests.async5- ~~~~~~~~~~~~~~4+requests.async5+~~~~~~~~~~~~~~6 7- This module implements the main Requests system, after monkey-patching8- the urllib2 module with eventlet or gevent..9-10- :copyright: (c) 2011 by Kenneth Reitz.11- :license: ISC, see LICENSE for more details.7+This module contains an asynchronous replica of ``requests.api``, powered8+by gevent. All API methods return a ``Request`` instance (as opposed to9+``Response``). A list of requests can be sent with ``map()``.10 """11 12+try:13+ import gevent14+ from gevent import monkey as curious_george15+except ImportError:16+ raise RuntimeError('Gevent is required for requests.async.')17 15-from __future__ import absolute_import18+# Monkey-patch.19+curious_george.patch_all(thread=False)20 17-import urllib18-import urllib221+from . import api22+from .hooks import dispatch_hook23+from .packages.urllib3.poolmanager import PoolManager24 20-from urllib2 import HTTPError25 26+__all__ = (27+ 'map',28+ 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'29+)30 23-try:24- import eventlet25- eventlet.monkey_patch()26-except ImportError:27- pass31 29-if not 'eventlet' in locals():30- try:31- from gevent import monkey32- monkey.patch_all()33- except ImportError:34- pass32+def _patched(f):33+ """Patches a given API function to not send."""34 35+ def wrapped(*args, **kwargs):36+ return f(*args, _return_request=True, **kwargs)37 37-if not 'eventlet' in locals():38- raise ImportError('No Async adaptations of urllib2 found!')38+ return wrapped39 40 41-from .core import *41+def _send(r, pools=None):42+ """Sends a given Request object."""43+44+ if pools:45+ r._pools = pools46+47+ r.send()48+49+ # Post-request hook.50+ r = dispatch_hook('post_request', r.hooks, r)51+52+ # Response manipulation hook.53+ r.response = dispatch_hook('response', r.hooks, r.response)54+55+ return r.response56+57+58+# Patched requests.api functions.59+get = _patched(api.get)60+head = _patched(api.head)61+post = _patched(api.post)62+put = _patched(api.put)63+patch = _patched(api.patch)64+delete = _patched(api.delete)65+request = _patched(api.request)66+67+68+def map(requests, keep_alive=False):69+ """Concurrently converts a list of Requests to Responses.70+71+ :param requests: a collection of Request objects.72+ :param keep_alive: If True, HTTP Keep-Alive will be used.73+ """74+75+ if keep_alive:76+ pools = PoolManager(num_pools=len(requests), maxsize=1)77+ else:78+ pools = None79+80+ jobs = [gevent.spawn(_send, r, pools=pools) for r in requests]81+ gevent.joinall(jobs)82+83+ return [r.response for r in requests]84+85+86+87+deleted:requests/config.py-46 removed
1-# -*- coding: utf-8 -*-2-3-"""4-requests.config5-~~~~~~~~~~~~~~~6-7-This module provides the Requests settings feature set.8-9-settings parameters:10-11-TODO: Verify!!!12-TODO: Make sure format is acceptabl/cool13-- :base_headers: - Sets default User-Agent to `python-requests.org`14-- :accept_gzip: - Whether or not to accept gzip-compressed data15-- :proxies: - http proxies?16-- :verbose: - display verbose information?17-- :timeout: - timeout time until request terminates18-- :max_redirects: - maximum number of allowed redirects?19-- :decode_unicode: - whether or not to accept unicode?20-21-Used globally22-23-"""24-25-26-class Settings(object):27-28- def __init__(self, **kwargs):29- super(Settings, self).__init__()30-31- def __getattribute__(self, key):32- return object.__getattribute__(self, key)33-34-35-settings = Settings()36-37-settings.base_headers = {'User-Agent': 'python-requests.org'}38-settings.accept_gzip = True39-settings.proxies = None40-settings.verbose = None41-settings.timeout = None42-settings.max_redirects = 3043-settings.decode_unicode = True44-45-#: Use socket.setdefaulttimeout() as fallback?46-settings.timeout_fallback = Truemodified:requests/core.py+9 added-2 removed
1 # -*- coding: utf-8 -*-2 3+# __4+# /__) _ _ _ _ _/ _5+# / ( (- (/ (/ (- _) / _)6+# /7+8 """9 requests.core10 ~~~~~~~~~~~~~11 3 unmodified lines15 :license: ISC, see LICENSE for more details.16 17 """18 19+20 __title__ = 'requests'21 __version__ = '0.6.2 (dev)'22 __build__ = 0x00060223 __author__ = 'Kenneth Reitz'24 __license__ = 'ISC'25 __copyright__ = 'Copyright 2011 Kenneth Reitz'26 27+import logging28+logging.basicConfig()29 30 from api import *23-from config import settings31 from exceptions import *25-from models import HTTPError, Request, Response32+from models import Request, Response33 from sessions import session34 from status_codes import codes35 36 import utilsmodified:requests/exceptions.py+6 added
9 unmodified lines10 class RequestException(Exception):11 """There was an ambiguous exception that occured while handling your12 request."""13 14+class AuthenticationError(RequestException):15+ """The authentication credentials provided were invalid."""16 17+18 class AuthenticationError(RequestException):19 """The authentication credentials provided were invalid."""20 21 3 unmodified lines25 26 class URLRequired(RequestException):27 """A valid URL is required to make a request."""28 29+class InvalidMethod(RequestException):30+ """An inappropriate method was attempted."""31 32+33 class InvalidMethod(RequestException):34 """An inappropriate method was attempted."""35 36 2 unmodified linesmodified:requests/models.py+205 added-350 removed
5 unmodified lines6 7 """8 9 import urllib10-import urllib211-import socket12-import codecs10 import zlib11+from Cookie import SimpleCookie12+from urlparse import urlparse, urlunparse, urljoin13 14+from .packages import urllib315+from .packages.urllib3.filepost import encode_multipart_formdata16 16-from urllib2 import HTTPError17-from urlparse import urlparse18-from datetime import datetime19-20-from .config import settings21-from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler17+from ._config import get_config18 from .structures import CaseInsensitiveDict23-from .packages.poster.encode import multipart_encode24-from .packages.poster.streaminghttp import register_openers, get_handlers25-from .utils import get_clean_url, dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip19+from .utils import *20 from .status_codes import codes27-from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects21+from .exceptions import RequestException, Timeout, URLRequired, TooManyRedirects22+from .packages.urllib3.poolmanager import PoolManager23 24 25 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)26 4 unmodified lines31 """32 33 def __init__(self,34 url=None, headers=dict(), files=None, method=None, data=dict(),40- params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,41- allow_redirects=False, proxies=None):35+ params=dict(), auth=None, cookies=None, timeout=None, redirect=False,36+ allow_redirects=False, proxies=None, config=None, hooks=None,37+ _pools=None):38 39+ if cookies is None:40+ cookies = {}41+42+43 #: Float describ the timeout of the request.44 # (Use socket.setdefaulttimeout() as fallback)45 self.timeout = timeout46 47 #: Request URL.48 self.url = url49 50 #: Dictonary of HTTP Headers to attach to the :class:`Request <Request>`.51- self.headers = headers51+ self.headers = headers or {}52 53 #: Dictionary of files to multipart upload (``{filename: content}``).54- self.files = files54+ self.files = files or {}55 56 #: HTTP Method to use.57 self.method = method58 14 unmodified lines73 74 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})75 self.proxies = proxies76 77- self.data, self._enc_data = self._encode_params(data)78- self.params, self._enc_params = self._encode_params(params)77+ self.config = get_config(config)78 79+ self.data = data80+ self._enc_data = encode_params(data)81+ self.params = params82+ self._enc_params = encode_params(params)83+84 #: :class:`Response <Response>` instance, containing85 #: content and metadata of HTTP Response, once :attr:`sent <send>`.86 self.response = Response()87 84- if isinstance(auth, (list, tuple)):85- auth = AuthObject(*auth)86- if not auth:87- auth = auth_manager.get_auth(self.url)88-88 #: :class:`AuthObject` to attach to :class:`Request <Request>`.89 self.auth = auth90 91 #: CookieJar to attach to :class:`Request <Request>`.93- self.cookiejar = cookiejar92+ self.cookies = cookies93 94 #: True if Request has been sent.95 self.sent = False96 97 # Header manipulation and defaults.98 100- if settings.accept_gzip:101- settings.base_headers.update({'Accept-Encoding': 'gzip'})99+ if self.config.get('accept_gzip'):100+ self.headers.update({'Accept-Encoding': 'gzip'})101 102 if headers:103 headers = CaseInsensitiveDict(self.headers)104 else:105 headers = CaseInsensitiveDict()106 108- for (k, v) in settings.base_headers.items():107+ for (k, v) in self.config.get('base_headers').items():108 if k not in headers:109 headers[k] = v110 111 self.headers = headers112 113+ self.hooks = hooks114+ self._pools = _pools115+116 def __repr__(self):117 return '<Request [%s]>' % (self.method)118 119 def _checks(self):1 unmodified line121 122 if not self.url:123 raise URLRequired124 123- def _get_opener(self):124- """Creates appropriate opener object for urllib2."""125-126- _handlers = []127-128- if self.cookiejar is not None:129- _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))130-131- if self.auth:132- if not isinstance(self.auth.handler,133- (urllib2.AbstractBasicAuthHandler,134- urllib2.AbstractDigestAuthHandler)):135-136- # TODO: REMOVE THIS COMPLETELY137- auth_manager.add_password(138- self.auth.realm, self.url,139- self.auth.username,140- self.auth.password)141-142- self.auth.handler = self.auth.handler(auth_manager)143- auth_manager.add_auth(self.url, self.auth)144-145- _handlers.append(self.auth.handler)146-147- if self.proxies:148- _handlers.append(urllib2.ProxyHandler(self.proxies))149-150- _handlers.append(HTTPRedirectHandler)151-152- if not _handlers:153- return urllib2.urlopen154-155- if self.data or self.files:156- _handlers.extend(get_handlers())157-158- opener = urllib2.build_opener(*_handlers)159-160- if self.headers:161- # Allow default headers in the opener to be overloaded162- normal_keys = [k.capitalize() for k in self.headers]163- for key, val in opener.addheaders[:]:164- if key not in normal_keys:165- continue166- # Remove it, we have a value to take its place167- opener.addheaders.remove((key, val))168-169- return opener.open170-125 def _build_response(self, resp, is_error=False):126 """Build internal :class:`Response <Response>` object127 from given response.128 """129 130 def build(resp):131 132 response = Response()179- response.status_code = getattr(resp, 'code', None)133 181- try:182- response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))183- response.fo = resp134+ # Pass settings over.135+ response.config = self.config136 185- if self.cookiejar:137+ # Fallback to None if there's no staus_code, for whatever reason.138+ response.status_code = getattr(resp, 'status', None)139 187- response.cookies = dict_from_cookiejar(self.cookiejar)140+ # Make headers case-insensitive.141+ response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))142 189- except AttributeError:190- pass143+ # Start off with our local cookies.144+ cookies = self.cookies or dict()145 146+ # Add new cookies from the server.147+ if 'set-cookie' in response.headers:148+ cookie_header = response.headers['set-cookie']149+150+ c = SimpleCookie()151+ c.load(cookie_header)152+153+ for k,v in c.items():154+ cookies.update({k: v.value})155+156+ # Save cookies in Response.157+ response.cookies = cookies158+159+ # Save original resopnse for later.160+ response.raw = resp161+162+ # TODO: ?163 if is_error:164 response.error = resp165 195- response.url = getattr(resp, 'url', None)196-166 return response167 168+ # Request collector.169 history = []170 171+ # Create the lone response object.172 r = build(resp)173+ self.cookies.update(r.cookies)174 175+ # Store the HTTP response, just in case.176+ r._response = resp177+178+ # It's a redirect, and we're not already in a redirect loop.179 if r.status_code in REDIRECT_STATI and not self.redirect:180 181 while (182+ # There's a `Location` header.183 ('location' in r.headers) and184+185+ # See other response.186 ((r.status_code is codes.see_other) or187+188+ # Opt-in to redirects for non- idempotent methods.189 (self.allow_redirects))190 ):191 192+ # We already redirected. Don't keep it alive.211- r.fo.close()193+ # r.raw.close()194 213- if not len(history) < settings.max_redirects:195+ # Woah, this is getting crazy.196+ if len(history) >= self.config.get('max_redirects'):197 raise TooManyRedirects()198 199+ # Add the old request to the history collector.200 history.append(r)201 218- url = get_clean_url(r.headers['location'], parent_url=r.url)202+ url = get_clean_url(r.headers['location'], parent_url=self.url)203 204+ # If 303, convert to idempotent GET.205 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4206 if r.status_code is codes.see_other:207 method = 'GET'208 else:209 method = self.method210 211+ # Create the new Request.212 request = Request(227- url, self.headers, self.files, method,228- self.data, self.params, self.auth, self.cookiejar,213+ url=url,214+ headers=self.headers,215+ files=self.files,216+ method=method,217+ data=self.data,218+ # params=self.params,219+ params=None,220+ auth=self.auth,221+ cookies=self.cookies,222+ _pools=self._pools,223+ config=self.config,224+225+ # Flag as part of a redirect loop.226 redirect=True227 )228+229+ # Send her away!230 request.send()231 r = request.response232 233+ self.cookies.update(r.cookies or {})234+235+ # Insert collected history.236 r.history = history237 238+ # Attach Response to Request.239 self.response = r240+241+ # Give Response some context.242 self.response.request = self243 239- @staticmethod240- def _encode_params(data):241- """Encode parameters in a piece of data.244 243- If the data supplied is a dictionary, encodes each parameter in it, and244- returns a list of tuples containing the encoded parameters, and a urlencoded245- version of that.245+ def send(self, anyway=False):246+ """Sends the shit."""247 247- Otherwise, assumes the data is already encoded appropriately, and248- returns it twice.249- """248+ # Safety check.249+ self._checks()250 251- if hasattr(data, 'items'):252- result = []253- for k, vs in data.items():254- for v in isinstance(vs, list) and vs or [vs]:255- result.append((k.encode('utf-8') if isinstance(k, unicode) else k,256- v.encode('utf-8') if isinstance(v, unicode) else v)257- )258- return (result, urllib.urlencode(result, doseq=True))251+ # Build the final URL.252+ url = build_url(self.url, self.params)253 260- else:261- return data, data254+ # Nottin' on you.255+ body = None256+ content_type = None257 263- def _build_url(self):264- """Build the actual URL to use."""258+ # Multi-part file uploads.259+ if self.files:260+ if not isinstance(self.data, basestring):261+ fields = self.data.copy()262+ for (k, v) in self.files.items():263+ fields.update({k: (k, v.read())})264+ (body, content_type) = encode_multipart_formdata(fields)265 266- self.url = get_clean_url(self.url)267-268- if self._enc_params:269- if urlparse(self.url).query:270- return '%s&%s' % (self.url, self._enc_params)266+ # Setup form data.267+ if self.data and (not body):268+ if isinstance(self.data, basestring):269+ body = self.data270 else:272- return '%s?%s' % (self.url, self._enc_params)273- else:274- return self.url271+ body = encode_params(self.data)272+ content_type = 'application/x-www-form-urlencoded'273 276- def send(self, anyway=False):277- """Sends the request. Returns True of successful, false if not.278- If there was an HTTPError during transmission,279- self.response.status_code will contain the HTTPError code.274+ # Setup cookies.275 281- Once a request is successfully sent, `sent` will equal True.276+ # Add content-type if it wasn't explicitly provided.277+ if (content_type) and (not 'content-type' in self.headers):278+ self.headers['Content-Type'] = content_type279 283- :param anyway: If True, request will be sent, even if it has284- already been sent.285- """280+ # Only send the Request if new or forced.281+ if (anyway) or (not self.sent):282 287- self._checks()283+ try:284+ # Create a new HTTP connection, since one wasn't passed in.285+ if not self._pools:286 289- # Logging290- if settings.verbose:291- settings.verbose.write('%s %s %s\n' % (292- datetime.now().isoformat(), self.method, self.url293- ))287+ # Create a pool manager for this one connection.288+ pools = PoolManager(289+ num_pools=self.config.get('max_connections'),290+ maxsize=1,291+ timeout=self.timeout292+ )293 295- url = self._build_url()296- if self.method in ('GET', 'HEAD', 'DELETE'):297- req = _Request(url, method=self.method)298- else:294+ # Create a connection.295+ connection = pools.connection_from_url(url)296 300- if self.files:301- register_openers()297+ # One-off request. Delay fetching the content until needed.298+ do_block = False299+ else:300+ # Create a connection.301+ connection = self._pools.connection_from_url(url)302 303- if self.data:304- self.files.update(self.data)303+ # Syntax sugar.304+ pools = self._pools305 306- datagen, headers = multipart_encode(self.files)307- req = _Request(url, data=datagen, headers=headers, method=self.method)306+ # Part of a connection pool, so no fancy stuff. Sorry!307+ do_block = True308 309- else:310- req = _Request(url, data=self._enc_data, method=self.method)309+ if self.cookies:310+ # Skip if 'cookie' header is explicitly set.311+ if 'cookie' not in self.headers:312 312- if self.headers:313- for k, v in self.headers.iteritems():314- req.add_header(k, v)313+ # Simple cookie with our dict.314+ c = SimpleCookie()315+ c.load(self.cookies)316 316- if not self.sent or anyway:317+ # Turn it into a header.318+ cookie_header = c.output(header='').strip()319 318- try:319- opener = self._get_opener()320- try:320+ # Attach Cookie header to request.321+ self.headers['Cookie'] = cookie_header322 322- resp = opener(req, timeout=self.timeout)323+ # Create the connection.324+ r = connection.urlopen(325+ method=self.method,326+ url=url,327+ body=body,328+ headers=self.headers,329+ redirect=False,330+ assert_same_host=False,331+ preload_content=do_block,332+ decode_content=False333+ )334 324- except TypeError, err:325- # timeout argument is new since Python v2.6326- if not 'timeout' in str(err):327- raise335+ # Set the pools manager for redirections, if allowed.336+ if self.config.get('keep_alive') and pools:337+ self._pools = pools338 329- if settings.timeout_fallback:330- # fall-back and use global socket timeout (This is not thread-safe!)331- old_timeout = socket.getdefaulttimeout()332- socket.setdefaulttimeout(self.timeout)339 334- resp = opener(req)340+ # except (urllib2.HTTPError, urllib2.URLError), why:341+ except Exception, why:342+ print why.__dict__343+ # if hasattr(why, 'reason'):344+ # if isinstance(why.reason, socket.timeout):345+ # why = Timeout(why)346 336- if settings.timeout_fallback:337- # restore gobal timeout338- socket.setdefaulttimeout(old_timeout)347+ # self._build_response(why, is_error=True)348+ print 'FUCK'349+ print why350 340- if self.cookiejar is not None:341- self.cookiejar.extract_cookies(resp, req)342-343- except (urllib2.HTTPError, urllib2.URLError), why:344- if hasattr(why, 'reason'):345- if isinstance(why.reason, socket.timeout):346- why = Timeout(why)347-348- self._build_response(why, is_error=True)349-351 else:352+ # self.response = Response.from_urllib3()351- self._build_response(resp)353+ self._build_response(r)354 self.response.ok = True355 356 self.sent = self.response.ok357 21 unmodified lines379 #: value of a ``'Content-Encoding'`` response header.380 self.headers = CaseInsensitiveDict()381 382 #: File-like object representation of response (for advanced usage).381- self.fo = None383+ self.raw = None384 383- #: Final URL location of Response.384- self.url = None385-385 #: True if no :attr:`error` occured.386 self.ok = False387 388 #: Resulting :class:`HTTPError` of request, if one occured.9 unmodified lines398 399 #: A dictionary of Cookies the server sent back.400 self.cookies = None401 402+ #: A dictionary of configuration.403+ self.config = None404+405 def __repr__(self):406 return '<Response [%s]>' % (self.status_code)407 408 def __nonzero__(self):12 unmodified lines421 'already consumed')422 423 def generate():424 while 1:423- chunk = self.fo.read(chunk_size)425+ chunk = self.raw.read(chunk_size)426 if not chunk:427 break428 yield chunk429 self._content_consumed = True428- gen = generate()430+ gen = generate431+432 if 'gzip' in self.headers.get('content-encoding', ''):433 gen = stream_decode_gzip(gen)434+435 if decode_unicode is None:436 decode_unicode = settings.decode_unicode437+438 if decode_unicode:439 gen = stream_decode_response_unicode(gen, self)440+441 return gen442 443+444 @property445 def content(self):446 """Content of the response, in bytes or unicode447 (if available).2 unmodified lines450 if self._content is not None:451 return self._content452 453 if self._content_consumed:447- raise RuntimeError('The content for this response was '448- 'already consumed')454+ raise RuntimeError(455+ 'The content for this response was already consumed')456 457 # Read the contents.451- self._content = self.fo.read()458+ self._content = self.raw.read() or self.raw.data459 460 # Decode GZip'd content.461 if 'gzip' in self.headers.get('content-encoding', ''):462 try:1 unmodified line464 except zlib.error:465 pass466 467 # Decode unicode content.461- if settings.decode_unicode:468+ if self.config.get('decode_unicode'):469 self._content = get_unicode_from_response(self)470 471 self._content_consumed = True472 return self._content473 474+475 def raise_for_status(self):468- """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""476+ """Raises stored :class:`HTTPError` or :class:`URLError`,477+ if one occured.478+ """479+480 if self.error:481 raise self.error482 483+ if (self.status_code >= 300) and (self.status_code < 400):484+ raise Exception('300 yo')485 473-class AuthManager(object):474- """Requests Authentication Manager."""486+ elif (self.status_code >= 400) and (self.status_code < 500):487+ raise Exception('400 yo')488 476- def __new__(cls):477- singleton = cls.__dict__.get('__singleton__')478- if singleton is not None:479- return singleton480-481- cls.__singleton__ = singleton = object.__new__(cls)482-483- return singleton484-485- def __init__(self):486- self.passwd = {}487- self._auth = {}488-489- def __repr__(self):490- return '<AuthManager [%s]>' % (self.method)491-492- def add_auth(self, uri, auth):493- """Registers AuthObject to AuthManager."""494-495- uri = self.reduce_uri(uri, False)496-497- # try to make it an AuthObject498- if not isinstance(auth, AuthObject):499- try:500- auth = AuthObject(*auth)501- except TypeError:502- pass503-504- self._auth[uri] = auth505-506- def add_password(self, realm, uri, user, passwd):507- """Adds password to AuthManager."""508- # uri could be a single URI or a sequence509- if isinstance(uri, basestring):510- uri = [uri]511-512- reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])513-514- if reduced_uri not in self.passwd:515- self.passwd[reduced_uri] = {}516- self.passwd[reduced_uri] = (user, passwd)517-518- def find_user_password(self, realm, authuri):519- for uris, authinfo in self.passwd.iteritems():520- reduced_authuri = self.reduce_uri(authuri, False)521- for uri in uris:522- if self.is_suburi(uri, reduced_authuri):523- return authinfo524-525- return (None, None)526-527- def get_auth(self, uri):528- (in_domain, in_path) = self.reduce_uri(uri, False)529-530- for domain, path, authority in (531- (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()532- ):533- if in_domain == domain:534- if path in in_path:535- return authority536-537- def reduce_uri(self, uri, default_port=True):538- """Accept authority or URI and extract only the authority and path."""539-540- # note HTTP URLs do not have a userinfo component541- parts = urllib2.urlparse.urlsplit(uri)542-543- if parts[1]:544- # URI545- scheme = parts[0]546- authority = parts[1]547- path = parts[2] or '/'548- else:549- # host or host:port550- scheme = None551- authority = uri552- path = '/'553-554- host, port = urllib2.splitport(authority)555-556- if default_port and port is None and scheme is not None:557- dport = {"http": 80,558- "https": 443,559- }.get(scheme)560- if dport is not None:561- authority = "%s:%d" % (host, dport)562-563- return authority, path564-565- def is_suburi(self, base, test):566- """Check if test is below base in a URI tree567-568- Both args must be URIs in reduced form.569- """570- if base == test:571- return True572- if base[0] != test[0]:573- return False574- common = urllib2.posixpath.commonprefix((base[1], test[1]))575- if len(common) == len(base[1]):576- return True577- return False578-579- def empty(self):580- self.passwd = {}581-582- def remove(self, uri, realm=None):583- # uri could be a single URI or a sequence584- if isinstance(uri, basestring):585- uri = [uri]586-587- for default_port in True, False:588- reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])589- del self.passwd[reduced_uri][realm]590-591- def __contains__(self, uri):592- # uri could be a single URI or a sequence593- if isinstance(uri, basestring):594- uri = [uri]595-596- uri = tuple([self.reduce_uri(u, False) for u in uri])597-598- if uri in self.passwd:599- return True600-601- return False602-603-auth_manager = AuthManager()604-605-606-class AuthObject(object):607- """The :class:`AuthObject` is a simple HTTP Authentication token.608-609- When given to a Requests function, it enables Basic HTTP Authentication610- for that Request. You can also enable Authorization for domain realms611- with AutoAuth. See AutoAuth for more details.612-613- :param username: Username to authenticate with.614- :param password: Password for given username.615- :param realm: (optional) the realm this auth applies to616- :param handler: (optional) basic || digest || proxy_basic || proxy_digest617- """618-619- _handlers = {620- 'basic': HTTPBasicAuthHandler,621- 'forced_basic': HTTPForcedBasicAuthHandler,622- 'digest': HTTPDigestAuthHandler,623- 'proxy_basic': urllib2.ProxyBasicAuthHandler,624- 'proxy_digest': urllib2.ProxyDigestAuthHandler625- }626-627- def __init__(self, username, password, handler='forced_basic', realm=None):628- self.username = username629- self.password = password630- self.realm = realm631-632- if isinstance(handler, basestring):633- self.handler = self._handlers.get(handler.lower(), HTTPForcedBasicAuthHandler)634- else:635- self.handler = handler489+ elif (self.status_code >= 500) and (self.status_code < 600):490+ raise Exception('500 yo')deleted:requests/monkeys.py-142 removed
1-#-*- coding: utf-8 -*-2-3-"""4-requests.monkeys5-~~~~~~~~~~~~~~~~6-7-Urllib2 Monkey patches.8-9-"""10-11-import re12-import urllib213-14-15-class Request(urllib2.Request):16- """Hidden wrapper around the urllib2.Request object. Allows for manual17- setting of HTTP methods.18- """19-20- def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):21- urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)22- self.method = method23-24- def get_method(self):25- if self.method:26- return self.method27-28- return urllib2.Request.get_method(self)29-30-31-class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):32- """HTTP Redirect handler."""33- def http_error_301(self, req, fp, code, msg, headers):34- pass35-36- http_error_302 = http_error_303 = http_error_307 = http_error_30137-38-39-class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):40- """HTTP Basic Auth Handler with authentication loop fixes."""41-42- def __init__(self, *args, **kwargs):43- urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44- self.retried_req = None45- self.retried = 046-47- def reset_retry_count(self):48- # Python 2.6.5 will call this on 401 or 407 errors and thus loop49- # forever. We disable reset_retry_count completely and reset in50- # http_error_auth_reqed instead.51- pass52-53- def http_error_auth_reqed(self, auth_header, host, req, headers):54- # Reset the retry counter once for each request.55- if req is not self.retried_req:56- self.retried_req = req57- self.retried = 058-59- return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(60- self, auth_header, host, req, headers61- )62-63-64-class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):65- """HTTP Basic Auth Handler with forced Authentication."""66-67- auth_header = 'Authorization'68- rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'69- 'realm=(["\'])(.*?)\\2', re.I)70-71- def __init__(self, *args, **kwargs):72- HTTPBasicAuthHandler.__init__(self, *args, **kwargs)73-74- def http_error_401(self, req, fp, code, msg, headers):75- url = req.get_full_url()76- response = self._http_error_auth_reqed('www-authenticate', url, req, headers)77- self.reset_retry_count()78- return response79-80- http_error_404 = http_error_40181-82- def _http_error_auth_reqed(self, authreq, host, req, headers):83-84- authreq = headers.get(authreq, None)85-86- if self.retried > 5:87- # retry sending the username:password 5 times before failing.88- raise urllib2.HTTPError(req.get_full_url(), 401, "basic auth failed",89- headers, None)90- else:91- self.retried += 192-93- if authreq:94-95- mo = self.rx.search(authreq)96-97- if mo:98- scheme, quote, realm = mo.groups()99-100- if scheme.lower() == 'basic':101- response = self.retry_http_basic_auth(host, req, realm)102-103- if response and response.code not in (401, 404):104- self.retried = 0105- return response106- else:107- response = self.retry_http_basic_auth(host, req, 'Realm')108-109- if response and response.code not in (401, 404):110- self.retried = 0111- return response112-113-114-class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):115-116- def __init__(self, *args, **kwargs):117- urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)118- self.retried_req = None119-120- def reset_retry_count(self):121- # Python 2.6.5 will call this on 401 or 407 errors and thus loop122- # forever. We disable reset_retry_count completely and reset in123- # http_error_auth_reqed instead.124- pass125-126- def http_error_auth_reqed(self, auth_header, host, req, headers):127- # Reset the retry counter once for each request.128- if req is not self.retried_req:129- self.retried_req = req130- self.retried = 0131- # In python < 2.5 AbstractDigestAuthHandler raises a ValueError if132- # it doesn't know about the auth type requested. This can happen if133- # somebody is using BasicAuth and types a bad password.134-135- try:136- return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(137- self, auth_header, host, req, headers)138- except ValueError, inst:139- arg = inst.args[0]140- if arg.startswith("AbstractDigestAuthHandler doesn't know "):141- return142- raisemodified:requests/sessions.py+90 added-25 removed
10 unmodified lines11 12 import cookielib13 14 from . import api15+from ._config import get_config16 from .utils import add_dict_to_cookiejar17+from .packages.urllib3.poolmanager import PoolManager18 19 20+def merge_kwargs(local_kwarg, default_kwarg):21+ """Merges kwarg dictionaries.22+23+ If a local key in the dictionary is set to None, it will be removed.24+ """25+26+ # Bypass if not a dictionary (e.g. timeout)27+ if not hasattr(local_kwarg, 'items'):28+ return local_kwarg29+30+ # Update new values.31+ kwargs = default_kwarg.copy()32+ kwargs.update(local_kwarg)33+34+ # Remove keys that are set to None.35+ for (k,v) in local_kwarg.items():36+ if v is None:37+ del kwargs[k]38+39+ return kwargs40+41+42+43 class Session(object):44 """A Requests session."""45 21- __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']46+ __attrs__ = [47+ 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',48+ 'config'49+ ]50 23- def __init__(self, **kwargs):51+ def __init__(self,52+ headers=None,53+ cookies=None,54+ auth=None,55+ timeout=None,56+ proxies=None,57+ hooks=None,58+ config=None):59 25- # Set up a CookieJar to be used by default26- self.cookies = cookielib.FileCookieJar()60+ self.headers = headers61+ self.cookies = cookies or {}62+ self.auth = auth63+ self.timeout = timeout64+ self.proxies = proxies65+ self.hooks = hooks66+ self.config = get_config(config)67 28- # Map args from kwargs to instance-local variables29- map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),30- kwargs.iterkeys(), kwargs.itervalues())68+ self.__pools = PoolManager(69+ num_pools=10,70+ maxsize=171+ )72 32- # Map and wrap requests.api methods73+ # Map and wrap requests.api methods.74 self._map_api_methods()75 76 def __repr__(self):77 return '<requests-client at 0x%x>' % (id(self))1 unmodified line79 def __enter__(self):80 return self81 82 def __exit__(self, *args):42- # print args83 pass84 85 def _map_api_methods(self):86 """Reads each available method from requests.api and decorates2 unmodified lines89 """90 91 def pass_args(func):92 def wrapper_func(*args, **kwargs):53- inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems()54- if k in self.__attrs__)55- # Combine instance-local values with kwargs values, with56- # priority to values in kwargs57- kwargs = dict(inst_attrs.items() + kwargs.items())93 59- # If a session request has a cookie_dict, inject the60- # values into the existing CookieJar instead.61- if isinstance(kwargs.get('cookies', None), dict):62- kwargs['cookies'] = add_dict_to_cookiejar(63- inst_attrs['cookies'], kwargs['cookies']64- )94+ # Argument collector.95+ _kwargs = {}96 66- if kwargs.get('headers', None) and inst_attrs.get('headers', None):67- kwargs['headers'].update(inst_attrs['headers'])97+ # Merge local and session arguments.98+ for attr in self.__attrs__:99+ # if attr == 'cookies':100+ # print getattr(self, attr)101+ # print kwargs.get(attr)102 69- return func(*args, **kwargs)103+ # Merge local and session dictionaries.104+ default_attr = getattr(self, attr)105+ local_attr = kwargs.get(attr)106+107+ # Cookies persist.108+ if attr == 'cookies':109+ local_attr = local_attr or {}110+111+ new_attr = merge_kwargs(local_attr, default_attr)112+113+ # Skip attributes that were set to None.114+ if new_attr is not None:115+ _kwargs[attr] = new_attr116+117+ # Make sure we didn't miss anything.118+ for (k, v) in kwargs.items():119+ if k not in _kwargs:120+ _kwargs[k] = v121+122+ # Add in PoolManager, if neccesary.123+ if self.config.get('keep_alive'):124+ _kwargs['_pools'] = self.__pools125+126+ # TODO: Persist cookies.127+ # print self.cookies128+129+ # print _kwargs.get('cookies')130+ # print '%%%'131+132+ r = func(*args, **_kwargs)133+ # print r.cookies134+ self.cookies.update(r.cookies or {})135+ return r136 return wrapper_func137 138 # Map and decorate each function available in requests.api73- map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))),74- api.__all__)139+ map(lambda fn: setattr(self, fn, pass_args(getattr(api, fn))), api.__all__)140 141 142 def session(**kwargs):143 """Returns a :class:`Session` for context-managment."""2 unmodified linesmodified:requests/utils.py+44 added-4 removed
13 unmodified lines14 import cookielib15 import re16 import urllib17 import zlib18-18 from urlparse import urlparse, urlunparse, urljoin19 20+21+def encode_params(params):22+ """Encode parameters in a piece of data.23+24+ If the data supplied is a dictionary, encodes each parameter in it, and25+ returns a list of tuples containing the encoded parameters, and a urlencoded26+ version of that.27+28+ Otherwise, assumes the data is already encoded appropriately, and29+ returns it twice.30+ """31+32+ if hasattr(params, 'items'):33+ result = []34+ for k, vs in params.items():35+ for v in isinstance(vs, list) and vs or [vs]:36+ result.append(37+ (38+ k.encode('utf-8') if isinstance(k, unicode) else k,39+ v.encode('utf-8') if isinstance(v, unicode) else v40+ )41+ )42+ return urllib.urlencode(result, doseq=True)43+44+ else:45+ return params46+47 def get_clean_url(url, parent_url=None):48 # Handle redirection without scheme (see: RFC 1808 Section 4)49 if url.startswith('//'):50 parsed_rurl = urlparse(parent_url)18 unmodified lines69 url = urljoin(parent_url, url)70 71 return url72 73+def build_url(url, query_params):74+ """Build the actual URL to use."""75+76+ url = get_clean_url(url)77+78+ query_params = encode_params(query_params)79+80+ if query_params:81+ if urlparse(url).query:82+ return '%s&%s' % (url, query_params)83+ else:84+ return '%s?%s' % (url, query_params)85+ else:86+ return url87+88 def header_expand(headers):89 """Returns an HTTP Header value string from a dictionary.90 91 Example expansion::37 unmodified lines129 130 return ''.join(collector)131 132 92-def dict_from_cookiejar(cj):133+def dict_from_cookiejar(cookies):134 """Returns a key/value dictionary from a CookieJar.135 136 :param cj: CookieJar object to extract cookies from.137 """138 139 cookie_dict = {}140 100- for _, cookies in cj._cookies.items():141+ for _, cookies in cookies.items():142 for _, cookies in cookies.items():143 for cookie in cookies.values():103- # print cookie144 cookie_dict[cookie.name] = cookie.value145 146 return cookie_dict147 248 unmodified linesmodified:AUTHORS+6 added
5 unmodified lines6 7 - Kenneth Reitz <me@kennethreitz.com>8 9 10+Urllib311+```````12+13+- Andrey Petrov <shazow@gmail.com>14+15+16 Patches and Suggestions17 ```````````````````````18 19 - Various Pocoo Members35 unmodified linesdeleted:NOTICE-12 removed
1-Request includes some vendorized python libraries to ease installation.2-3-Poster License4-==============5-6-Copyright (c) 2010 Chris AtLee7-8-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:9-10-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.11-12-THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.modified:setup.py+1 added-1 removed
32 unmodified lines33 url='http://python-requests.org',34 packages= [35 'requests',36 'requests.packages',37- 'requests.packages.poster'37+ 'requests.packages.urllib3'38 ],39 install_requires=required,40 license='ISC',41 classifiers=(12 unmodified lines