Skip to content
Myr

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

32 files+1661 added−1330 removed

deleted:debian/changelog-5 removed
1python-requests (0.4.1-0) testing; urgency=low23 * Initial Debian package45 -- Bruno Clermont <bruno.clermont@gmail.com> Thu, 26 May 2011 16:25:00 -0500
deleted:debian/compat-1 removed
15
deleted:debian/control-13 removed
1Source: python-requests2Section: python3Priority: optional4Maintainer: Bruno Clermont <bruno.clermont@gmail.com>5Homepage: https://github.com/bclermont/requests6Bugs: https://github.com/bclermont/requests/issues7Build-Depends: debhelper, python-support89Package: python-requests10Architecture: all11Depends: ${python:Depends}, python-support12Provides: ${python:Provides}13Description: Python HTTP Requests for Humans.
deleted:debian/docs-1 removed
1docs/user/*.rst
deleted:debian/pyversions-1 removed
12.4-
deleted:debian/rules-42 removed
1#!/usr/bin/make -f23# Verbose mode4#export DH_VERBOSE=156clean:7 dh_testdir8 dh_testroot910 rm -rf build requests.egg-info11# find django-sentry/ -name *.pyc | xargs rm -f1213 dh_clean1415build:16 dh_testdir1718 python setup.py build1920install:21 dh_testdir22 dh_installdirs2324 python setup.py install --root $(CURDIR)/debian/python-requests2526binary-indep: install2728binary-arch: install29 dh_install30 dh_installdocs31# dh_installchangelogs32 dh_compress33 dh_fixperms34 dh_pysupport35 dh_gencontrol36 dh_installdeb37 dh_md5sums38 dh_builddeb -- -Z lzma -z93940binary: 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 module2122Support for streaming HTTP uploads, and multipart/form-data encoding2324```poster.version``` is a 3-tuple of integers representing the version number.25New releases of poster will always have a version number that compares greater26than an older version of poster.27New in version 0.6."""2829from __future__ import absolute_import3031from . import streaminghttp32from . import encode3334version = (0, 8, 0) # Thanks JP!
deleted:requests/packages/poster/encode.py-414 removed
1"""multipart/form-data encoding module23This module provides functions that faciliate encoding name/value pairs4as multipart/form-data suitable for a HTTP POST or PUT request.56multipart/form-data is the standard way to upload files over HTTP"""78__all__ = ['gen_boundary', 'encode_and_quote', 'MultipartParam',9 'encode_string', 'encode_file_header', 'get_body_size', 'get_headers',10 'multipart_encode']1112try:13 import uuid14 def gen_boundary():15 """Returns a random string to use as the boundary for a message"""16 return uuid.uuid4().hex17except 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()2324import urllib, re, os, mimetypes25try:26 from email.header import Header27except ImportError:28 # Python 2.429 from email.Header import Header3031def 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 None3637 if isinstance(data, unicode):38 data = data.encode("utf-8")39 return urllib.quote_plus(data)4041def _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)4950class MultipartParam(object):51 """Represents a single parameter in a multipart/form-data request5253 ``name`` is the name of this parameter.5455 If ``value`` is set, it must be a string or unicode object to use as the56 data for this parameter.5758 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.6061 If ``filetype`` is set, it is used as the Content-Type for this parameter.62 If unset it defaults to "text/plain; charset=utf8"6364 If ``filesize`` is set, it specifies the length of the file ``fileobj``6566 If ``fileobj`` is set, it must be a file-like object that supports67 .read().6869 Both ``value`` and ``fileobj`` must not be set, doing so will70 raise a ValueError assertion.7172 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.7778 ``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)9798 self.filesize = filesize99 self.fileobj = fileobj100 self.cb = cb101102 if self.value is not None and self.fileobj is not None:103 raise ValueError("Only one of value or fileobj may be specified")104105 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")116117 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)122123 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")128129 @classmethod130 def from_file(cls, paramname, filename):131 """Returns a new MultipartParam object constructed from the local132 file at ``filename``.133134 ``filesize`` is determined by os.path.getsize(``filename``)135136 ``filetype`` is determined by mimetypes.guess_type(``filename``)[0]137138 ``filename`` is set to os.path.basename(``filename``)139 """140141 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"))145146 @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 values151152 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()157158 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 = None175176 retval.append(cls(name=name, filename=filename,177 filetype=filetype, fileobj=value))178 else:179 retval.append(cls(name, value))180 return retval181182 def encode_hdr(self, boundary):183 """Returns the header of the encoding of this parameter"""184 boundary = encode_and_quote(boundary)185186 headers = ["--%s" % boundary]187188 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.name193194 headers.append("Content-Disposition: %s" % disposition)195196 if self.filetype:197 filetype = self.filetype198 else:199 filetype = "text/plain; charset=utf-8"200201 headers.append("Content-Type: %s" % filetype)202203 headers.append("")204 headers.append("")205206 return "\r\n".join(headers)207208 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.value214215 if re.search("^--%s$" % re.escape(boundary), value, re.M):216 raise ValueError("boundary found in encoded string")217218 return "%s%s\r\n" % (self.encode_hdr(boundary), value)219220 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)258259 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)266267 return len(self.encode_hdr(boundary)) + 2 + valuesize268269def 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."""273274 return MultipartParam(name, value).encode(boundary)275276def 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.280281 ``boundary`` is the boundary string used throughout a single request to282 separate variables.283284 ``paramname`` is the name of the variable in this request.285286 ``filesize`` is the size of the file data.287288 ``filename`` if specified is the filename to give to this field. This289 field is only useful to the server for determining the original filename.290291 ``filetype`` if specified is the MIME type of this file.292293 The actual file data should be sent after this header has been sent.294 """295296 return MultipartParam(paramname, filesize=filesize, filename=filename,297 filetype=filetype).encode_hdr(boundary)298299def 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) + 6304305def 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 headers313314class multipart_yielder:315 def __init__(self, params, boundary, cb):316 self.params = params317 self.boundary = boundary318 self.cb = cb319320 self.i = 0321 self.p = None322 self.param_iter = None323 self.current = 0324 self.total = get_body_size(params, boundary)325326 def __iter__(self):327 return self328329 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 = None342343 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 block354355 self.p = self.params[self.i]356 self.param_iter = self.p.iter_encode(self.boundary)357 self.i += 1358 return self.next()359360 def reset(self):361 self.i = 0362 self.current = 0363 for param in self.params:364 param.reset()365366def multipart_encode(params, boundary=None, cb=None):367 """Encode ``params`` as multipart/form-data.368369 ``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().374375 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.379380 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.384385 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.389390 Examples:391392 >>> datagen, headers = multipart_encode( [("key", "value1"), ("key", "value2")] )393 >>> s = "".join(datagen)394 >>> assert "value2" in s and "value1" in s395396 >>> p = MultipartParam("key", "value2")397 >>> datagen, headers = multipart_encode( [("key", "value1"), p] )398 >>> s = "".join(datagen)399 >>> assert "value2" in s and "value1" in s400401 >>> datagen, headers = multipart_encode( {"key": "value1"} )402 >>> s = "".join(datagen)403 >>> assert "value2" not in s and "value1" in s404405 """406 if boundary is None:407 boundary = gen_boundary()408 else:409 boundary = urllib.quote_plus(boundary)410411 headers = get_headers(params, boundary)412 params = MultipartParam.from_params(params)413414 return multipart_yielder(params, boundary, cb), headers
deleted:requests/packages/poster/streaminghttp.py-199 removed
1"""Streaming HTTP uploads module.23This module extends the standard httplib and urllib2 objects so that4iterable objects can be used in the body of HTTP requests.56In most cases all one should have to do is call :func:`register_openers()`7to register the new streaming http handlers which will take priority over8the default handlers, and then you can use iterable objects in the body9of HTTP requests.1011**N.B.** You must specify a Content-Length header if using an iterable object12since there is no way to determine in advance the total size that will be13yielded, and there is no way to reset an interator.1415Example usage:1617>>> from StringIO import StringIO18>>> import urllib2, poster.streaminghttp1920>>> opener = poster.streaminghttp.register_openers()2122>>> s = "Test file data"23>>> f = StringIO(s)2425>>> req = urllib2.Request("http://localhost:5000", f,26... {'Content-Length': str(len(s))})27"""2829import httplib, urllib2, socket30from httplib import NotConnected3132__all__ = ['StreamingHTTPConnection', 'StreamingHTTPRedirectHandler',33 'StreamingHTTPHandler', 'register_openers']3435if hasattr(httplib, 'HTTPS'):36 __all__.extend(['StreamingHTTPSHandler', 'StreamingHTTPSConnection'])3738class _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.4344 ``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()5455 # 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 raise8687class StreamingHTTPConnection(_StreamingHTTPMixin, httplib.HTTPConnection):88 """Subclass of `httplib.HTTPConnection` that overrides the `send()` method89 to support iterable body objects"""9091class StreamingHTTPRedirectHandler(urllib2.HTTPRedirectHandler):92 """Subclass of `urllib2.HTTPRedirectHandler` that overrides the93 `redirect_request` method to properly handle redirected POST requests9495 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 """99100 handler_order = urllib2.HTTPRedirectHandler.handler_order - 1101102 # 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.105106 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)133134class StreamingHTTPHandler(urllib2.HTTPHandler):135 """Subclass of `urllib2.HTTPHandler` that uses136 StreamingHTTPConnection as its http connection class."""137138 handler_order = urllib2.HTTPHandler.handler_order - 1139140 def http_open(self, req):141 """Open a StreamingHTTPConnection for the given request"""142 return self.do_open(StreamingHTTPConnection, req)143144 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)156157if 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"""162163 class StreamingHTTPSHandler(urllib2.HTTPSHandler):164 """Subclass of `urllib2.HTTPSHandler` that uses165 StreamingHTTPSConnection as its http connection class."""166167 handler_order = urllib2.HTTPSHandler.handler_order - 1168169 def https_open(self, req):170 return self.do_open(StreamingHTTPSConnection, req)171172 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)182183184def get_handlers():185 handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186 if hasattr(httplib, "HTTPS"):187 handlers.append(StreamingHTTPSHandler)188 return handlers189 190def register_openers():191 """Register the streaming http handlers in the global urllib2 default192 opener object.193194 Returns the created OpenerDirector object."""195 opener = urllib2.build_opener(*get_handlers())196197 urllib2.install_opener(opener)198199 return opener
added: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.php67"""8NTLM authenticating pool, contributed by erikcederstran910Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=1011"""1213import httplib14from logging import getLogger15from ntlm import ntlm1617from urllib3 import HTTPSConnectionPool181920log = getLogger(__name__)212223class NTLMConnectionPool(HTTPSConnectionPool):24 """25 Implements an NTLM authentication version of an urllib3 connection pool26 """2728 scheme = 'https'2930 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 = pw4344 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))5051 headers = {}52 headers['Connection'] = 'Keep-Alive'53 req_header = 'Authorization'54 resp_header = 'www-authenticate'5556 conn = httplib.HTTPSConnection(host=self.host, port=self.port)5758 # 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))6869 # 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 = None7273 # 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]))8283 # 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))104105 res.fp = None106 log.debug('Connection established')107 return conn108109 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.php67"""8urllib3 - Thread-safe connection pooling and re-using.9"""1011__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"12__license__ = "MIT"13__version__ = "$Rev$"141516from .connectionpool import (17 HTTPConnectionPool,18 HTTPSConnectionPool,19 connection_from_url,20 get_host,21 make_headers)222324from .exceptions import (25 HTTPError,26 MaxRetryError,27 SSLError,28 TimeoutError)2930from .poolmanager import PoolManager31from .response import HTTPResponse32from .filepost import encode_multipart_formdata
added: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.php67from collections import MutableMapping, deque8910__all__ = ['RecentlyUsedContainer']111213class AccessEntry(object):14 __slots__ = ('key', 'is_valid')1516 def __init__(self, key, is_valid=True):17 self.key = key18 self.is_valid = is_valid192021class 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 """2627 # TODO: Make this threadsafe. _prune_invalidated_entries should be the28 # only real pain-point for this.2930 # 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 = 103435 def __init__(self, maxsize=10):36 self._maxsize = maxsize3738 self._container = {}3940 # We use a deque to to store our keys ordered by the last access.41 self.access_log = deque()4243 # 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 = {}4748 # Trigger a heap cleanup when we get past this size49 self.access_log_limit = maxsize * self.CLEANUP_FACTOR5051 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 = False5758 new_entry = AccessEntry(key)5960 self.access_lookup[key] = new_entry61 self.access_log.appendleft(new_entry)6263 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()6768 if not p.is_valid:69 continue # Invalidated entry, skip7071 del self._container[p.key]72 del self.access_lookup[p.key]73 num -= 17475 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)7879 def _get_ordered_access_keys(self):80 # Used for testing81 return [e.key for e in self.access_log if e.is_valid]8283 def __getitem__(self, key):84 item = self._container.get(key)8586 if not item:87 return8889 # Insert new entry with new high priority, also implicitly invalidates90 # the old entry.91 self._push_entry(key)9293 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()9798 return item99100 def __setitem__(self, key, item):101 # Add item to our container and access log102 self._container[key] = item103 self._push_entry(key)104105 # Discard invalid and excess entries106 self._prune_entries(len(self._container) - self._maxsize)107108109 def __delitem__(self, key):110 self._invalidate_entry(key)111 del self._container[key]112 del self._access_lookup[key]113114 def __len__(self):115 return len(self.access_log)116117 def __iter__(self):118 return self._container.__iter__()119120 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.php67import logging8import socket91011from urllib import urlencode12from httplib import HTTPConnection, HTTPSConnection, HTTPException13from Queue import Queue, Empty, Full14from select import select15from socket import error as SocketError, timeout as SocketTimeout161718try:19 import ssl20 BaseSSLError = ssl.SSLError21except ImportError:22 ssl = None23 BaseSSLError = None242526from .filepost import encode_multipart_formdata27from .response import HTTPResponse28from .exceptions import (29 SSLError,30 MaxRetryError,31 TimeoutError,32 HostChangedError,33 EmptyPoolError)343536log = logging.getLogger(__name__)3738_Default = object()394041## Connection objects (extension of httplib)4243class VerifiedHTTPSConnection(HTTPSConnection):44 """45 Based on httplib.HTTPSConnection but wraps the socket with46 SSL certification.47 """4849 def __init__(self, **kwargs):50 HTTPSConnection.__init__(self, **kwargs)51 self.cert_reqs = None52 self.ca_certs = None5354 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 }6162 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_certs6667 def connect(self):68 # Add certificate verification69 sock = socket.create_connection((self.host, self.port), self.timeout)7071 # 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)767778## Pool objects7980class ConnectionPool(object):81 pass828384class HTTPConnectionPool(ConnectionPool):85 """86 Thread-safe connection pool for one host.8788 host89 Host used for this HTTP Connection (e.g. "localhost"), passed into90 httplib.HTTPConnection()9192 port93 Port used for this HTTP Connection (None is equivalent to 80), passed94 into httplib.HTTPConnection()9596 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()100101 timeout102 Socket timeout for each individual connection, can be a float. None103 disables timeout.104105 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.110111 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.117118 headers119 Headers to include with all requests, unless other headers are given120 explicitly.121 """122123 scheme = 'http'124125 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 {}134135 # Fill the queue up so that doing get() on it will block properly136 for _ in xrange(maxsize):137 self.pool.put(None)138139 # These are mostly for testing and debugging purposes.140 self.num_connections = 0141 self.num_requests = 0142143 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)151152 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)160161 # 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()166167 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 then172173 return conn or self._new_conn()174175 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)188189 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 += 1196197 if timeout is _Default:198 timeout = self.timeout199200201 conn.request(method, url, **httplib_request_kw)202 conn.sock.settimeout(timeout)203 httplib_response = conn.getresponse()204205206 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))210211 return httplib_response212213214 def is_same_host(self, url):215 return (url.startswith('/') or216 get_host(url) == (self.scheme, self.host, self.port))217218 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.223224 method225 HTTP request method (such as GET, POST, PUT, etc.)226227 body228 Data to send in the request body (useful for creating229 POST requests, see HTTPConnectionPool.post_url for230 more convenience).231232 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.236237 retries238 Number of retries to allow before raising239 a MaxRetryError exception.240241 redirect242 Automatically handle redirects (status codes 301, 302, 303, 307),243 each redirect counts as a retry.244245 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.249250 timeout251 If specified, overrides the default timeout for this one request.252253 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.257258 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)``.265266 Additional parameters are passed to267 ``HTTPResponse.from_httplib(r, **response_kw)``268 """269 if headers is None:270 headers = self.headers271272 if retries < 0:273 raise MaxRetryError("Max retries exceeded for url: %s" % url)274275 if release_conn is None:276 release_conn = response_kw.get('preload_content', True)277278 # 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)283284 raise HostChangedError("Connection pool with host '%s' tried to "285 "open a foreign host: %s" % (host, url))286287 conn = None288289 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 '!'298299 # Import httplib's response into our own wrapper object300 response = HTTPResponse.from_httplib(httplib_response,301 pool=self,302 connection=conn,303 **response_kw)304305 if release_conn:306 # The connection will be released manually in the ``finally:``307 response.connection = None308309 # else:310 # The connection will be put back into the pool when311 # ``response.release_conn()`` is called (implicitly by312 # ``response.read()``)313314 except (SocketTimeout, Empty), e:315 # Timed out either by socket or queue316 raise TimeoutError("Request timed out after %f seconds" %317 self.timeout)318319 except (BaseSSLError), e:320 # SSL certificate error321 raise SSLError(e)322323 except (HTTPException, SocketError), e:324 # Connection broken, discard. It will be replaced next _get_conn().325 conn = None326327 finally:328 if conn and release_conn:329 # Put the connection back to be reused330 self._put_conn(conn)331332 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 again337338 # 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)347348 return response349350 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).354355 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)362363 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).369370 Supports an optional ``fields`` parameter of key/value strings AND371 key/filetuple. A filetuple is a (filename, data) tuple. For example:372373 fields = {374 'foo': 'bar',375 'foofile': ('foofile.txt', 'contents of foofile'),376 }377378 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.383384 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.387388 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')399400 headers = headers or {}401 headers.update({'Content-Type': content_type})402403 return self.urlopen('POST', url, body, headers=headers,404 retries=retries, redirect=redirect, **response_kw)405406407class HTTPSConnectionPool(HTTPConnectionPool):408 """409 Same as HTTPConnectionPool, but HTTPS.410 """411412 scheme = 'https'413414 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):419420 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_certs427428 def _new_conn(self):429 """430 Return a fresh HTTPSConnection.431 """432433 self.num_connections += 1434 log.info("Starting new HTTPS connection (%d): %s"435 % (self.num_connections, self.host))436437 if not ssl:438 return HTTPSConnection(host=self.host, port=self.port)439440 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 connection444445446## Helpers447448def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,449 basic_auth=None):450 """451 Shortcuts for generating request headers.452453 keep_alive454 If true, adds 'connection: keep-alive' header.455456 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.461462 user_agent463 String representing the user-agent you want, such as464 "python-urllib3/0.6"465466 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_encoding479480 if user_agent:481 headers['user-agent'] = user_agent482483 if keep_alive:484 headers['connection'] = 'keep-alive'485486 if basic_auth:487 headers['authorization'] = 'Basic ' + \488 basic_auth.encode('base64').strip()489490 return headers491492493def get_host(url):494 """495 Given a url, return its scheme, host and port (None if it's not there).496497 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, port515516517def connection_from_url(url, **kw):518 """519 Given a url, return an HTTP(S)ConnectionPool instance of its host.520521 This is a shortcut for not having to determine the host of the url522 before creating an HTTP(S)ConnectionPool instance.523524 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.php67## Exceptions89class HTTPError(Exception):10 "Base exception used by this module."11 pass121314class SSLError(Exception):15 "Raised when SSL certificate fails in an HTTPS connection."16 pass171819class MaxRetryError(HTTPError):20 "Raised when the maximum number of retries is exceeded."21 pass222324class TimeoutError(HTTPError):25 "Raised when a socket timeout occurs."26 pass272829class HostChangedError(HTTPError):30 "Raised when an existing pool gets a request for a foreign host."31 pass3233class EmptyPoolError(HTTPError):34 "Raised when a pool runs out of connections and no more are allowed."35 pass
added: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.php67import codecs8import mimetools9import mimetypes1011try:12 from cStringIO import StringIO13except ImportError:14 from StringIO import StringIO # pylint: disable-msg=W0404151617writer = codecs.lookup('utf-8')[3]181920def get_content_type(filename):21 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'222324def encode_multipart_formdata(fields, boundary=None):25 body = StringIO()26 if boundary is None:27 boundary = mimetools.choose_boundary()2829 for fieldname, value in fields.iteritems():30 body.write('--%s\r\n' % (boundary))3132 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')4344 if isinstance(data, int):45 data = str(data) # Backwards compatibility4647 if isinstance(data, unicode):48 writer(body).write(data)49 else:50 body.write(data)5152 body.write('\r\n')5354 body.write('--%s--\r\n' % (boundary))5556 content_type = 'multipart/form-data; boundary=%s' % boundary5758 return body.getvalue(), content_type
added: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.php67from ._collections import RecentlyUsedContainer8from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, get_host91011pool_classes_by_scheme = {12 'http': HTTPConnectionPool,13 'https': HTTPSConnectionPool,14}1516port_by_scheme = {17 'http': 80,18 'https': 443,19}202122class PoolManager(object):23 """24 Allows for arbitrary requests while transparently keeping track of25 necessary connection pools for you.2627 num_pools28 Number of connection pools to cache before discarding the least recently29 used pool.3031 Additional parameters are used to create fresh ConnectionPool instances.3233 """3435 # TODO: Make sure there are no memory leaks here.3637 def __init__(self, num_pools=10, **connection_pool_kw):38 self.connection_pool_kw = connection_pool_kw3940 self.pools = RecentlyUsedContainer(num_pools)41 self.recently_used_pools = []4243 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)484950 # 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 pool5556 # 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)5960 self.pools[pool_key] = pool6162 return pool6364 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)7172 port = port or port_by_scheme.get(scheme, 80)7374 return self.connection_from_host(host, port=port, scheme=scheme)7576 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.php67import gzip8import logging9import zlib101112try:13 from cStringIO import StringIO14except ImportError:15 from StringIO import StringIO # pylint: disable-msg=W0404161718from .exceptions import HTTPError192021log = logging.getLogger(__name__)222324def decode_gzip(data):25 gzipper = gzip.GzipFile(fileobj=StringIO(data))26 return gzipper.read()272829def decode_deflate(data):30 try:31 return zlib.decompress(data)32 except zlib.error:33 return zlib.decompress(data, -zlib.MAX_WBITS)343536class HTTPResponse(object):37 """38 HTTP Response container.3940 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is41 loaded and decoded on-demand when the ``data`` property is accessed.4243 Extra parameters for behaviour not present in httplib.HTTPResponse:4445 preload_content46 If True, the response's body will be preloaded during construction.4748 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.5253 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 """5859 CONTENT_DECODERS = {60 'gzip': decode_gzip,61 'deflate': decode_deflate,62 }6364 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 = strict7273 self._decode_content = decode_content74 self._body = None75 self._fp = None76 self._original_response = original_response7778 self._pool = pool79 self._connection = connection8081 if hasattr(body, 'read'):82 self._fp = body8384 if preload_content:85 self._body = self.read(decode_content=decode_content)8687 def release_conn(self):88 if not self._pool or not self._connection:89 return9091 self._pool._put_conn(self._connection)92 self._connection = None9394 @property95 def data(self):96 # For backwords-compat with earlier urllib3 0.4 and earlier.97 if self._body:98 return self._body99100 if self._fp:101 return self.read(decode_content=self._decode_content,102 cache_content=True)103104 def read(self, amt=None, decode_content=True, cache_content=False):105 """106 Similar to ``httplib.HTTPResponse.read(amt=None)``.107108 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.112113 decode_content114 If True, will attempt to decode the body based on the115 'content-encoding' header. (Overridden if ``amt`` is set.)116117 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)126127 data = self._fp and self._fp.read(amt)128129 try:130131 if amt:132 return data133134 if not decode_content or not decoder:135 if cache_content:136 self._body = data137138 return data139140 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)145146 if cache_content:147 self._body = data148149 return data150151 finally:152153 if self._original_response and self._original_response.isclosed():154 self.release_conn()155156 @staticmethod157 def from_httplib(r, **response_kw):158 """159 Given an httplib.HTTPResponse instance ``r``, return a corresponding160 urllib3.HTTPResponse object.161162 Remaining parameters are passed to the HTTPResponse constructor, along163 with ``original_response=r``.164 """165166 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)174175 # Backwards-compatibility methods for httplib.HTTPResponse176 def getheaders(self):177 return self.headers178179 def getheader(self, name, default=None):180 return self.headers.get(name, default)
modified:requests/packages/__init__.py+1 added-1 removed
1from __future__ import absolute_import23from . import poster3from . import urllib3
added:requests/_config.py+52 added
1# -*- coding: utf-8 -*-23"""4requests.config5~~~~~~~~~~~~~~~67This module provides the Requests configuration defaults.89settings parameters:1011- :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?1819"""2021def get_config(config=None, default_config=None):22 """Merges two given configurations."""2324 # Allow raw calls.25 if config is None:26 config=dict()2728 # Use the module-level defaults, if none is given.29 if default_config is None:30 default_config = defaults.copy()313233 d = default_config.copy()34 d.update(config)3536 return d373839# Module-level defaults.40defaults = dict()4142defaults['base_headers'] = {'User-Agent': 'python-requests.org'}43defaults['accept_gzip'] = True44defaults['proxies'] = {}45defaults['verbose'] = None46defaults['timeout'] = None47defaults['max_redirects'] = 3048defaults['decode_unicode'] = True49defaults['keep_alive'] = True50defaults['max_connections'] = 105152
modified:requests/api.py+23 added-12 removed
2 unmodified lines
3"""4requests.api5~~~~~~~~~~~~67This module impliments the Requests API.7This module implements the Requests API.89:copyright: (c) 2011 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1314import config15from .models import Request, Response, AuthObject14from ._config import get_config15from .models import Request, Response16from .status_codes import codes17from .hooks import dispatch_hook18from .utils import cookiejar_from_dict, header_expand19
2 unmodified lines
222324def 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):2829 """Constructs and sends a :class:`Request <Request>`.30 Returns :class:`Response <Response>` object.31
7 unmodified lines
39 :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 """4546 method = str(method).upper()47 config = get_config(config)4849 if cookies is None:50 cookies = {}5149 cookies = cookiejar_from_dict(cookies)52 # cookies = cookiejar_from_dict(cookies)5354 # Expand header values55 if headers:56 for k, v in headers.items() or {}:
4 unmodified lines
61 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 )7475 # Arguments manipulation hook.76 args = dispatch_hook('args', hooks, args)7778 # Create Request object.79 r = Request(**args)8081 # Pre-request hook.82 r = dispatch_hook('pre_request', hooks, r)8384 # Only construct the request (for async)85 if _return_request:86 return r8788 # Send the HTTP Request.89 r.send()9091 # TODO: Add these hooks inline.92 # Post-request hook.93 r = dispatch_hook('post_request', hooks, r)9495 # Response manipulation hook.
8 unmodified lines
104 :param url: URL for the new :class:`Request` object.105 :param **kwargs: Optional arguments that ``request`` takes.106 """10797 if "allow_redirects" not in kwargs:98 kwargs["allow_redirects"] = True108 if 'allow_redirects' not in kwargs:109 kwargs['allow_redirects'] = True110111 return request('get', url, **kwargs)112113
3 unmodified lines
117 :param url: URL for the new :class:`Request` object.118 :param **kwargs: Optional arguments that ``request`` takes.119 """120110 if "allow_redirects" not in kwargs:111 kwargs["allow_redirects"] = True121 if 'allow_redirects' not in kwargs:122 kwargs['allow_redirects'] = True123124 return request('head', url, **kwargs)125126
41 unmodified lines
modified:requests/async.py+71 added-25 removed
1# -*- coding: utf-8 -*-23"""4 requests.async5 ~~~~~~~~~~~~~~4requests.async5~~~~~~~~~~~~~~67 This module implements the main Requests system, after monkey-patching8 the urllib2 module with eventlet or gevent..910 :copyright: (c) 2011 by Kenneth Reitz.11 :license: ISC, see LICENSE for more details.7This module contains an asynchronous replica of ``requests.api``, powered8by gevent. All API methods return a ``Request`` instance (as opposed to9``Response``). A list of requests can be sent with ``map()``.10"""1112try:13 import gevent14 from gevent import monkey as curious_george15except ImportError:16 raise RuntimeError('Gevent is required for requests.async.')1715from __future__ import absolute_import18# Monkey-patch.19curious_george.patch_all(thread=False)2017import urllib18import urllib221from . import api22from .hooks import dispatch_hook23from .packages.urllib3.poolmanager import PoolManager2420from urllib2 import HTTPError2526__all__ = (27 'map',28 'get', 'head', 'post', 'put', 'patch', 'delete', 'request'29)3023try:24 import eventlet25 eventlet.monkey_patch()26except ImportError:27 pass3129if not 'eventlet' in locals():30 try:31 from gevent import monkey32 monkey.patch_all()33 except ImportError:34 pass32def _patched(f):33 """Patches a given API function to not send."""3435 def wrapped(*args, **kwargs):36 return f(*args, _return_request=True, **kwargs)3737if not 'eventlet' in locals():38 raise ImportError('No Async adaptations of urllib2 found!')38 return wrapped394041from .core import *41def _send(r, pools=None):42 """Sends a given Request object."""4344 if pools:45 r._pools = pools4647 r.send()4849 # Post-request hook.50 r = dispatch_hook('post_request', r.hooks, r)5152 # Response manipulation hook.53 r.response = dispatch_hook('response', r.hooks, r.response)5455 return r.response565758# Patched requests.api functions.59get = _patched(api.get)60head = _patched(api.head)61post = _patched(api.post)62put = _patched(api.put)63patch = _patched(api.patch)64delete = _patched(api.delete)65request = _patched(api.request)666768def map(requests, keep_alive=False):69 """Concurrently converts a list of Requests to Responses.7071 :param requests: a collection of Request objects.72 :param keep_alive: If True, HTTP Keep-Alive will be used.73 """7475 if keep_alive:76 pools = PoolManager(num_pools=len(requests), maxsize=1)77 else:78 pools = None7980 jobs = [gevent.spawn(_send, r, pools=pools) for r in requests]81 gevent.joinall(jobs)8283 return [r.response for r in requests]84858687
deleted:requests/config.py-46 removed
1# -*- coding: utf-8 -*-23"""4requests.config5~~~~~~~~~~~~~~~67This module provides the Requests settings feature set.89settings parameters:1011TODO: Verify!!!12TODO: 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?2021Used globally2223"""242526class Settings(object):2728 def __init__(self, **kwargs):29 super(Settings, self).__init__()3031 def __getattribute__(self, key):32 return object.__getattribute__(self, key)333435settings = Settings()3637settings.base_headers = {'User-Agent': 'python-requests.org'}38settings.accept_gzip = True39settings.proxies = None40settings.verbose = None41settings.timeout = None42settings.max_redirects = 3043settings.decode_unicode = True4445#: Use socket.setdefaulttimeout() as fallback?46settings.timeout_fallback = True
modified:requests/core.py+9 added-2 removed
1# -*- coding: utf-8 -*-23# __4# /__) _ _ _ _ _/ _5# / ( (- (/ (/ (- _) / _)6# /78"""9requests.core10~~~~~~~~~~~~~11
3 unmodified lines
15:license: ISC, see LICENSE for more details.1617"""181920__title__ = 'requests'21__version__ = '0.6.2 (dev)'22__build__ = 0x00060223__author__ = 'Kenneth Reitz'24__license__ = 'ISC'25__copyright__ = 'Copyright 2011 Kenneth Reitz'2627import logging28logging.basicConfig()2930from api import *23from config import settings31from exceptions import *25from models import HTTPError, Request, Response32from models import Request, Response33from sessions import session34from status_codes import codes3536import utils
modified:requests/exceptions.py+6 added
9 unmodified lines
10class RequestException(Exception):11 """There was an ambiguous exception that occured while handling your12 request."""1314class AuthenticationError(RequestException):15 """The authentication credentials provided were invalid."""161718class AuthenticationError(RequestException):19 """The authentication credentials provided were invalid."""2021
3 unmodified lines
2526class URLRequired(RequestException):27 """A valid URL is required to make a request."""2829class InvalidMethod(RequestException):30 """An inappropriate method was attempted."""313233class InvalidMethod(RequestException):34 """An inappropriate method was attempted."""3536
2 unmodified lines
modified:requests/models.py+205 added-350 removed
5 unmodified lines
67"""89import urllib10import urllib211import socket12import codecs10import zlib11from Cookie import SimpleCookie12from urlparse import urlparse, urlunparse, urljoin1314from .packages import urllib315from .packages.urllib3.filepost import encode_multipart_formdata1616from urllib2 import HTTPError17from urlparse import urlparse18from datetime import datetime1920from .config import settings21from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPForcedBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler17from ._config import get_config18from .structures import CaseInsensitiveDict23from .packages.poster.encode import multipart_encode24from .packages.poster.streaminghttp import register_openers, get_handlers25from .utils import get_clean_url, dict_from_cookiejar, get_unicode_from_response, stream_decode_response_unicode, decode_gzip, stream_decode_gzip19from .utils import *20from .status_codes import codes27from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod, TooManyRedirects21from .exceptions import RequestException, Timeout, URLRequired, TooManyRedirects22from .packages.urllib3.poolmanager import PoolManager232425REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)26
4 unmodified lines
31 """3233 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):3839 if cookies is None:40 cookies = {}414243 #: Float describ the timeout of the request.44 # (Use socket.setdefaulttimeout() as fallback)45 self.timeout = timeout4647 #: Request URL.48 self.url = url4950 #: Dictonary of HTTP Headers to attach to the :class:`Request <Request>`.51 self.headers = headers51 self.headers = headers or {}5253 #: Dictionary of files to multipart upload (``{filename: content}``).54 self.files = files54 self.files = files or {}5556 #: HTTP Method to use.57 self.method = method58
14 unmodified lines
7374 # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})75 self.proxies = proxies7677 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)7879 self.data = data80 self._enc_data = encode_params(data)81 self.params = params82 self._enc_params = encode_params(params)8384 #: :class:`Response <Response>` instance, containing85 #: content and metadata of HTTP Response, once :attr:`sent <send>`.86 self.response = Response()8784 if isinstance(auth, (list, tuple)):85 auth = AuthObject(*auth)86 if not auth:87 auth = auth_manager.get_auth(self.url)8888 #: :class:`AuthObject` to attach to :class:`Request <Request>`.89 self.auth = auth9091 #: CookieJar to attach to :class:`Request <Request>`.93 self.cookiejar = cookiejar92 self.cookies = cookies9394 #: True if Request has been sent.95 self.sent = False9697 # Header manipulation and defaults.98100 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'})101102 if headers:103 headers = CaseInsensitiveDict(self.headers)104 else:105 headers = CaseInsensitiveDict()106108 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] = v110111 self.headers = headers112113 self.hooks = hooks114 self._pools = _pools115116 def __repr__(self):117 return '<Request [%s]>' % (self.method)118119 def _checks(self):
1 unmodified line
121122 if not self.url:123 raise URLRequired124123 def _get_opener(self):124 """Creates appropriate opener object for urllib2."""125126 _handlers = []127128 if self.cookiejar is not None:129 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))130131 if self.auth:132 if not isinstance(self.auth.handler,133 (urllib2.AbstractBasicAuthHandler,134 urllib2.AbstractDigestAuthHandler)):135136 # TODO: REMOVE THIS COMPLETELY137 auth_manager.add_password(138 self.auth.realm, self.url,139 self.auth.username,140 self.auth.password)141142 self.auth.handler = self.auth.handler(auth_manager)143 auth_manager.add_auth(self.url, self.auth)144145 _handlers.append(self.auth.handler)146147 if self.proxies:148 _handlers.append(urllib2.ProxyHandler(self.proxies))149150 _handlers.append(HTTPRedirectHandler)151152 if not _handlers:153 return urllib2.urlopen154155 if self.data or self.files:156 _handlers.extend(get_handlers())157158 opener = urllib2.build_opener(*_handlers)159160 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))168169 return opener.open170125 def _build_response(self, resp, is_error=False):126 """Build internal :class:`Response <Response>` object127 from given response.128 """129130 def build(resp):131132 response = Response()179 response.status_code = getattr(resp, 'code', None)133181 try:182 response.headers = CaseInsensitiveDict(getattr(resp.info(), 'dict', None))183 response.fo = resp134 # Pass settings over.135 response.config = self.config136185 if self.cookiejar:137 # Fallback to None if there's no staus_code, for whatever reason.138 response.status_code = getattr(resp, 'status', None)139187 response.cookies = dict_from_cookiejar(self.cookiejar)140 # Make headers case-insensitive.141 response.headers = CaseInsensitiveDict(getattr(resp, 'headers', None))142189 except AttributeError:190 pass143 # Start off with our local cookies.144 cookies = self.cookies or dict()145146 # Add new cookies from the server.147 if 'set-cookie' in response.headers:148 cookie_header = response.headers['set-cookie']149150 c = SimpleCookie()151 c.load(cookie_header)152153 for k,v in c.items():154 cookies.update({k: v.value})155156 # Save cookies in Response.157 response.cookies = cookies158159 # Save original resopnse for later.160 response.raw = resp161162 # TODO: ?163 if is_error:164 response.error = resp165195 response.url = getattr(resp, 'url', None)196166 return response167168 # Request collector.169 history = []170171 # Create the lone response object.172 r = build(resp)173 self.cookies.update(r.cookies)174175 # Store the HTTP response, just in case.176 r._response = resp177178 # 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:180181 while (182 # There's a `Location` header.183 ('location' in r.headers) and184185 # See other response.186 ((r.status_code is codes.see_other) or187188 # Opt-in to redirects for non- idempotent methods.189 (self.allow_redirects))190 ):191192 # We already redirected. Don't keep it alive.211 r.fo.close()193 # r.raw.close()194213 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()198199 # Add the old request to the history collector.200 history.append(r)201218 url = get_clean_url(r.headers['location'], parent_url=r.url)202 url = get_clean_url(r.headers['location'], parent_url=self.url)203204 # 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.method210211 # 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,224225 # Flag as part of a redirect loop.226 redirect=True227 )228229 # Send her away!230 request.send()231 r = request.response232233 self.cookies.update(r.cookies or {})234235 # Insert collected history.236 r.history = history237238 # Attach Response to Request.239 self.response = r240241 # Give Response some context.242 self.response.request = self243239 @staticmethod240 def _encode_params(data):241 """Encode parameters in a piece of data.244243 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."""247247 Otherwise, assumes the data is already encoded appropriately, and248 returns it twice.249 """248 # Safety check.249 self._checks()250251 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)253260 else:261 return data, data254 # Nottin' on you.255 body = None256 content_type = None257263 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)265266 self.url = get_clean_url(self.url)267268 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'273276 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.275281 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_type279283 :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):282287 self._checks()283 try:284 # Create a new HTTP connection, since one wasn't passed in.285 if not self._pools:286289 # 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 )293295 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)296300 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)302303 if self.data:304 self.files.update(self.data)303 # Syntax sugar.304 pools = self._pools305306 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 = True308309 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:312312 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)316316 if not self.sent or anyway:317 # Turn it into a header.318 cookie_header = c.output(header='').strip()319318 try:319 opener = self._get_opener()320 try:320 # Attach Cookie header to request.321 self.headers['Cookie'] = cookie_header322322 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 )334324 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 = pools338329 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)339334 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)346336 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 why350340 if self.cookiejar is not None:341 self.cookiejar.extract_cookies(resp, req)342343 except (urllib2.HTTPError, urllib2.URLError), why:344 if hasattr(why, 'reason'):345 if isinstance(why.reason, socket.timeout):346 why = Timeout(why)347348 self._build_response(why, is_error=True)349351 else:352 # self.response = Response.from_urllib3()351 self._build_response(resp)353 self._build_response(r)354 self.response.ok = True355356 self.sent = self.response.ok357
21 unmodified lines
379 #: value of a ``'Content-Encoding'`` response header.380 self.headers = CaseInsensitiveDict()381382 #: File-like object representation of response (for advanced usage).381 self.fo = None383 self.raw = None384383 #: Final URL location of Response.384 self.url = None385385 #: True if no :attr:`error` occured.386 self.ok = False387388 #: Resulting :class:`HTTPError` of request, if one occured.
9 unmodified lines
398399 #: A dictionary of Cookies the server sent back.400 self.cookies = None401402 #: A dictionary of configuration.403 self.config = None404405 def __repr__(self):406 return '<Response [%s]>' % (self.status_code)407408 def __nonzero__(self):
12 unmodified lines
421 'already consumed')422423 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 = generate431432 if 'gzip' in self.headers.get('content-encoding', ''):433 gen = stream_decode_gzip(gen)434435 if decode_unicode is None:436 decode_unicode = settings.decode_unicode437438 if decode_unicode:439 gen = stream_decode_response_unicode(gen, self)440441 return gen442443444 @property445 def content(self):446 """Content of the response, in bytes or unicode447 (if available).
2 unmodified lines
450 if self._content is not None:451 return self._content452453 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')456457 # Read the contents.451 self._content = self.fo.read()458 self._content = self.raw.read() or self.raw.data459460 # Decode GZip'd content.461 if 'gzip' in self.headers.get('content-encoding', ''):462 try:
1 unmodified line
464 except zlib.error:465 pass466467 # Decode unicode content.461 if settings.decode_unicode:468 if self.config.get('decode_unicode'):469 self._content = get_unicode_from_response(self)470471 self._content_consumed = True472 return self._content473474475 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 """479480 if self.error:481 raise self.error482483 if (self.status_code >= 300) and (self.status_code < 400):484 raise Exception('300 yo')485473class AuthManager(object):474 """Requests Authentication Manager."""486 elif (self.status_code >= 400) and (self.status_code < 500):487 raise Exception('400 yo')488476 def __new__(cls):477 singleton = cls.__dict__.get('__singleton__')478 if singleton is not None:479 return singleton480481 cls.__singleton__ = singleton = object.__new__(cls)482483 return singleton484485 def __init__(self):486 self.passwd = {}487 self._auth = {}488489 def __repr__(self):490 return '<AuthManager [%s]>' % (self.method)491492 def add_auth(self, uri, auth):493 """Registers AuthObject to AuthManager."""494495 uri = self.reduce_uri(uri, False)496497 # try to make it an AuthObject498 if not isinstance(auth, AuthObject):499 try:500 auth = AuthObject(*auth)501 except TypeError:502 pass503504 self._auth[uri] = auth505506 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]511512 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])513514 if reduced_uri not in self.passwd:515 self.passwd[reduced_uri] = {}516 self.passwd[reduced_uri] = (user, passwd)517518 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 authinfo524525 return (None, None)526527 def get_auth(self, uri):528 (in_domain, in_path) = self.reduce_uri(uri, False)529530 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 authority536537 def reduce_uri(self, uri, default_port=True):538 """Accept authority or URI and extract only the authority and path."""539540 # note HTTP URLs do not have a userinfo component541 parts = urllib2.urlparse.urlsplit(uri)542543 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 = '/'553554 host, port = urllib2.splitport(authority)555556 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)562563 return authority, path564565 def is_suburi(self, base, test):566 """Check if test is below base in a URI tree567568 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 False578579 def empty(self):580 self.passwd = {}581582 def remove(self, uri, realm=None):583 # uri could be a single URI or a sequence584 if isinstance(uri, basestring):585 uri = [uri]586587 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]590591 def __contains__(self, uri):592 # uri could be a single URI or a sequence593 if isinstance(uri, basestring):594 uri = [uri]595596 uri = tuple([self.reduce_uri(u, False) for u in uri])597598 if uri in self.passwd:599 return True600601 return False602603auth_manager = AuthManager()604605606class AuthObject(object):607 """The :class:`AuthObject` is a simple HTTP Authentication token.608609 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.612613 :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 """618619 _handlers = {620 'basic': HTTPBasicAuthHandler,621 'forced_basic': HTTPForcedBasicAuthHandler,622 'digest': HTTPDigestAuthHandler,623 'proxy_basic': urllib2.ProxyBasicAuthHandler,624 'proxy_digest': urllib2.ProxyDigestAuthHandler625 }626627 def __init__(self, username, password, handler='forced_basic', realm=None):628 self.username = username629 self.password = password630 self.realm = realm631632 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 -*-23"""4requests.monkeys5~~~~~~~~~~~~~~~~67Urllib2 Monkey patches.89"""1011import re12import urllib2131415class Request(urllib2.Request):16 """Hidden wrapper around the urllib2.Request object. Allows for manual17 setting of HTTP methods.18 """1920 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 = method2324 def get_method(self):25 if self.method:26 return self.method2728 return urllib2.Request.get_method(self)293031class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):32 """HTTP Redirect handler."""33 def http_error_301(self, req, fp, code, msg, headers):34 pass3536 http_error_302 = http_error_303 = http_error_307 = http_error_301373839class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):40 """HTTP Basic Auth Handler with authentication loop fixes."""4142 def __init__(self, *args, **kwargs):43 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44 self.retried_req = None45 self.retried = 04647 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 pass5253 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 = 05859 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(60 self, auth_header, host, req, headers61 )626364class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):65 """HTTP Basic Auth Handler with forced Authentication."""6667 auth_header = 'Authorization'68 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'69 'realm=(["\'])(.*?)\\2', re.I)7071 def __init__(self, *args, **kwargs):72 HTTPBasicAuthHandler.__init__(self, *args, **kwargs)7374 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 response7980 http_error_404 = http_error_4018182 def _http_error_auth_reqed(self, authreq, host, req, headers):8384 authreq = headers.get(authreq, None)8586 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 += 19293 if authreq:9495 mo = self.rx.search(authreq)9697 if mo:98 scheme, quote, realm = mo.groups()99100 if scheme.lower() == 'basic':101 response = self.retry_http_basic_auth(host, req, realm)102103 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')108109 if response and response.code not in (401, 404):110 self.retried = 0111 return response112113114class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):115116 def __init__(self, *args, **kwargs):117 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)118 self.retried_req = None119120 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 pass125126 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.134135 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 raise
modified:requests/sessions.py+90 added-25 removed
10 unmodified lines
1112import cookielib1314from . import api15from ._config import get_config16from .utils import add_dict_to_cookiejar17from .packages.urllib3.poolmanager import PoolManager181920def merge_kwargs(local_kwarg, default_kwarg):21 """Merges kwarg dictionaries.2223 If a local key in the dictionary is set to None, it will be removed.24 """2526 # Bypass if not a dictionary (e.g. timeout)27 if not hasattr(local_kwarg, 'items'):28 return local_kwarg2930 # Update new values.31 kwargs = default_kwarg.copy()32 kwargs.update(local_kwarg)3334 # Remove keys that are set to None.35 for (k,v) in local_kwarg.items():36 if v is None:37 del kwargs[k]3839 return kwargs40414243class Session(object):44 """A Requests session."""4521 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']46 __attrs__ = [47 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',48 'config'49 ]5023 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):5925 # 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)6728 # 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 )7232 # Map and wrap requests.api methods73 # Map and wrap requests.api methods.74 self._map_api_methods()7576 def __repr__(self):77 return '<requests-client at 0x%x>' % (id(self))
1 unmodified line
79 def __enter__(self):80 return self8182 def __exit__(self, *args):42 # print args83 pass8485 def _map_api_methods(self):86 """Reads each available method from requests.api and decorates
2 unmodified lines
89 """9091 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())9359 # 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 = {}9666 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)10269 return func(*args, **kwargs)103 # Merge local and session dictionaries.104 default_attr = getattr(self, attr)105 local_attr = kwargs.get(attr)106107 # Cookies persist.108 if attr == 'cookies':109 local_attr = local_attr or {}110111 new_attr = merge_kwargs(local_attr, default_attr)112113 # Skip attributes that were set to None.114 if new_attr is not None:115 _kwargs[attr] = new_attr116117 # Make sure we didn't miss anything.118 for (k, v) in kwargs.items():119 if k not in _kwargs:120 _kwargs[k] = v121122 # Add in PoolManager, if neccesary.123 if self.config.get('keep_alive'):124 _kwargs['_pools'] = self.__pools125126 # TODO: Persist cookies.127 # print self.cookies128129 # print _kwargs.get('cookies')130 # print '%%%'131132 r = func(*args, **_kwargs)133 # print r.cookies134 self.cookies.update(r.cookies or {})135 return r136 return wrapper_func137138 # 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__)140141142def session(**kwargs):143 """Returns a :class:`Session` for context-managment."""
2 unmodified lines
modified:requests/utils.py+44 added-4 removed
13 unmodified lines
14import cookielib15import re16import urllib17import zlib1818from urlparse import urlparse, urlunparse, urljoin192021def encode_params(params):22 """Encode parameters in a piece of data.2324 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.2728 Otherwise, assumes the data is already encoded appropriately, and29 returns it twice.30 """3132 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)4344 else:45 return params4647def 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 lines
69 url = urljoin(parent_url, url)7071 return url7273def build_url(url, query_params):74 """Build the actual URL to use."""7576 url = get_clean_url(url)7778 query_params = encode_params(query_params)7980 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 url8788def header_expand(headers):89 """Returns an HTTP Header value string from a dictionary.9091 Example expansion::
37 unmodified lines
129130 return ''.join(collector)13113292def dict_from_cookiejar(cj):133def dict_from_cookiejar(cookies):134 """Returns a key/value dictionary from a CookieJar.135136 :param cj: CookieJar object to extract cookies from.137 """138139 cookie_dict = {}140100 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.value145146 return cookie_dict147
248 unmodified lines
modified:AUTHORS+6 added
5 unmodified lines
67- Kenneth Reitz <me@kennethreitz.com>8910Urllib311```````1213- Andrey Petrov <shazow@gmail.com>141516Patches and Suggestions17```````````````````````1819- Various Pocoo Members
35 unmodified lines
deleted:NOTICE-12 removed
1Request includes some vendorized python libraries to ease installation.23Poster License4==============56Copyright (c) 2010 Chris AtLee78Permission 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:910The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.1112THE 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 lines
33 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