Merge branch 'develop' into urllib3
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: requests/api.py requests/exceptions.py requests/models.py
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 04bcab8, cd01aa4 · Browse files · 12 files·+108 added−71 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+108 added−71 removed
- other:+108 added−71 removed
Provenance
- Commit
d2894b3- Tree
347577e- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
04bcab8- Parent 2
cd01aa4
12 files changed+108 added−71 removed
modified:docs/index.rst+2 added-1 removed
39 unmodified lines40 ------------41 42 `Twitter, Inc <http://twitter.com>`_,43 a U.S. Federal Institution,44-and `Readability <http://readability.com>`_44+`Readability <http://readability.com>`_, and45+`Work for Pie <http://workforpie.com>`_46 use Requests internally.47 48 **Daniel Greenfeld**49 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to67 unmodified linesmodified:requests/api.py+22 added
64 unmodified lines65 files = files,66 auth = auth,67 timeout = timeout or config.settings.timeout,68 allow_redirects = allow_redirects,69+ proxies = proxies or config.settings.proxies,70+ method = method,71+ url = url,72+ data = data,73+ params = params,74+ headers = headers,75+ cookiejar = cookies,76+ files = files,77+ auth = auth,78+ timeout = timeout or config.settings.timeout,79+ allow_redirects = allow_redirects,80 proxies = proxies or config.settings.proxies81+ method=method,82+ url=url,83+ data=data,84+ params=params,85+ headers=headers,86+ cookiejar=cookies,87+ files=files,88+ auth=auth,89+ timeout=timeout or config.settings.timeout,90+ allow_redirects=allow_redirects,91+ proxies=proxies or config.settings.proxies,92 )93 94 # Arguments manipulation hook.95 args = dispatch_hook('args', hooks, args)86 unmodified linesmodified:requests/config.py+15 added
4 unmodified lines5 ~~~~~~~~~~~~~~~6 7 This module provides the Requests settings feature set.8 9+settings parameters:10+11+TODO: Verify!!!12+TODO: Make sure format is acceptabl/cool13+- :base_headers: - Sets default User-Agent to `python-requests.org`14+- :accept_gzip: - Whether or not to accept gzip-compressed data15+- :proxies: - http proxies?16+- :verbose: - display verbose information?17+- :timeout: - timeout time until request terminates18+- :max_redirects: - maximum number of allowed redirects?19+- :decode_unicode: - whether or not to accept unicode?20+21+Used globally22+23 """24 25+26 class Settings(object):27 28 def __init__(self, **kwargs):29 super(Settings, self).__init__()17 unmodified linesmodified:requests/core.py+3 added-3 removed
17 unmodified lines18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 21 22-from models import HTTPError, Request, Response22 from api import *23+from config import settings24 from exceptions import *25+from models import HTTPError, Request, Response26 from sessions import session27 from status_codes import codes27-from config import settings28 29-import utils29+import utilsmodified:requests/exceptions.py+18 added
4 unmodified lines5 ~~~~~~~~~~~~~~~6 7 """8 9+10 class RequestException(Exception):11 """There was an ambiguous exception that occured while handling your12 request."""13 14+class AuthenticationError(RequestException):15+ """The authentication credentials provided were invalid."""16+ 17+18+class AuthenticationError(RequestException):19+ """The authentication credentials provided were invalid."""20+21+22 class Timeout(RequestException):23 """The request timed out."""24 25+26 class URLRequired(RequestException):27 """A valid URL is required to make a request."""28 29+class InvalidMethod(RequestException):30+ """An inappropriate method was attempted."""31+32+33+class InvalidMethod(RequestException):34+ """An inappropriate method was attempted."""35+36+37 class TooManyRedirects(RequestException):38 """Too many redirects."""modified:requests/models.py+24 added-39 removed
28 unmodified lines29 30 REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31 32 33-33 class Request(object):34 """The :class:`Request <Request>` object. It carries out all functionality of35 Requests. Recommended interface is with the Requests functions.36 """57 unmodified lines94 95 #: True if Request has been sent.96 self.sent = False97 99-98 # Header manipulation and defaults.99 100 if settings.accept_gzip:101 settings.base_headers.update({'Accept-Encoding': 'gzip'})8 unmodified lines110 headers[k] = v111 112 self.headers = headers113 116-114 def __repr__(self):115 return '<Request [%s]>' % (self.method)116 120-117 def _checks(self):118 """Deterministic checks for consistency."""119 120 if not self.url:121 raise URLRequired122 127-123 def _get_opener(self):124 """Creates appropriate opener object for urllib2."""125 126 _handlers = []40 unmodified lines167 opener.addheaders.remove((key, val))168 169 return opener.open170 176-171 def _build_response(self, resp, is_error=False):172 """Build internal :class:`Response <Response>` object173 from given response.174 """175 182-176 def build(resp):177 178 response = Response()179 response.status_code = getattr(resp, 'status', None)3 unmodified lines183 response.raw = resp._raw184 185 # if self.cookiejar:186 187+ response.cookies = dict_from_cookiejar(self.cookiejar)188+189+190 # response.cookies = dict_from_cookiejar(self.cookiejar)191 192+ response.cookies = dict_from_cookiejar(self.cookiejar)193+194 except AttributeError:195 pass196 197 if is_error:198 response.error = resp199 200 return response201 204-202 # Request collector.203 history = []204 205 # Create the lone response object.70 unmodified lines276 277 # Give Response some context.278 self.response.request = self279 283-280 @staticmethod281 def _encode_params(data):282 """Encode parameters in a piece of data.283 9 unmodified lines293 result = []294 for k, vs in data.items():295 for v in isinstance(vs, list) and vs or [vs]:296 result.append((k.encode('utf-8') if isinstance(k, unicode) else k,301- v.encode('utf-8') if isinstance(v, unicode) else v))302- return result, urllib.urlencode(result, doseq=True)297+ v.encode('utf-8') if isinstance(v, unicode) else v)298+ )299+ return (result, urllib.urlencode(result, doseq=True))300+301 else:302 return data, data303 306-304 def _build_url(self):305 """Build the actual URL to use."""306 307 # Support for unicode domain names and paths.10 unmodified lines318 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")319 320 # Turn it back into a bytestring.321 self.url = str(urlunparse([scheme, netloc, path, params, query, fragment]))322+ self.url = str(urlunparse(323+ [scheme, netloc, path, params, query, fragment]324+ ))325 326 # Query Parameters?327 if self._enc_params:328 8 unmodified lines337 else:338 # Kosher URL.339 return self.url340 341-341 def send(self, connection=None, anyway=False):342 """Sends the shit."""343 344 # Safety check.85 unmodified lines430 settings.verbose.write('%s %s %s\n' % (431 datetime.now().isoformat(), self.method, self.url432 ))433 435-434 url = self._build_url()435 if self.method in ('GET', 'HEAD', 'DELETE'):436 req = _Request(url, method=self.method)437 else:10 unmodified lines448 else:449 req = _Request(url, data=self._enc_data, method=self.method)450 451 if self.headers:454- for k,v in self.headers.iteritems():452+ for k, v in self.headers.iteritems():453 req.add_header(k, v)454 455 if not self.sent or anyway:456 32 unmodified lines489 else:490 self._build_response(resp)491 self.response.ok = True492 495-493 self.sent = self.response.ok494 495 return self.sent496 497 498 class Response(object):502- """The core :class:`Response <Response>` object. All503- :class:`Request <Request>` objects contain a504- :class:`response <Response>` attribute, which is an instance505- of this class.499+ """The core :class:`Response <Response>` object.500+501+502+ All :class:`Request <Request>` objects contain a :class:`response503+ <Response>` attribute, which is an instance of this class.504 """505 506 def __init__(self):507 27 unmodified lines535 536 #: A dictionary of Cookies the server sent back.537 self.cookies = None538 541-539 def __repr__(self):540 return '<Response [%s]>' % (self.status_code)541 545-542 def __nonzero__(self):543 """Returns true if :attr:`status_code` is 'OK'."""544 545 return not self.error56 unmodified lines602 603 self._content_consumed = True604 return self._content605 610-606 def raise_for_status(self):607 """Raises stored :class:`HTTPError` or :class:`URLError`,608 if one occured.609 """3 unmodified lines613 614 if (self.status_code >= 300) and (self.status_code < 400):615 raise Exception('300 yo')616 617+618 elif (self.status_code >= 400) and (self.status_code < 500):619 raise Exception('400 yo')620 621 elif (self.status_code >= 500) and (self.status_code < 600):11 unmodified lines633 cls.__singleton__ = singleton = object.__new__(cls)634 635 return singleton636 641-637 def __init__(self):638 self.passwd = {}639 self._auth = {}640 646-641 def __repr__(self):642 return '<AuthManager [%s]>' % (self.method)643 650-644 def add_auth(self, uri, auth):645 """Registers AuthObject to AuthManager."""646 647 uri = self.reduce_uri(uri, False)6 unmodified lines654 pass655 656 self._auth[uri] = auth657 665-658 def add_password(self, realm, uri, user, passwd):659 """Adds password to AuthManager."""660 # uri could be a single URI or a sequence661 if isinstance(uri, basestring):4 unmodified lines666 if reduced_uri not in self.passwd:667 self.passwd[reduced_uri] = {}668 self.passwd[reduced_uri] = (user, passwd)669 678-670 def find_user_password(self, realm, authuri):671 for uris, authinfo in self.passwd.iteritems():672 reduced_authuri = self.reduce_uri(authuri, False)673 for uri in uris:1 unmodified line675 return authinfo676 677 return (None, None)678 688-679 def get_auth(self, uri):680 (in_domain, in_path) = self.reduce_uri(uri, False)681 682 for domain, path, authority in (2 unmodified lines685 if in_domain == domain:686 if path in in_path:687 return authority688 699-689 def reduce_uri(self, uri, default_port=True):690 """Accept authority or URI and extract only the authority and path."""691 692 # note HTTP URLs do not have a userinfo component20 unmodified lines713 authority = "%s:%d" % (host, dport)714 715 return authority, path716 728-717 def is_suburi(self, base, test):718 """Check if test is below base in a URI tree719 720 Both args must be URIs in reduced form.6 unmodified lines727 if len(common) == len(base[1]):728 return True729 return False730 743-731 def empty(self):732 self.passwd = {}733 747-734 def remove(self, uri, realm=None):735 # uri could be a single URI or a sequence736 if isinstance(uri, basestring):737 uri = [uri]1 unmodified line739 for default_port in True, False:740 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])741 del self.passwd[reduced_uri][realm]742 757-743 def __contains__(self, uri):744 # uri could be a single URI or a sequence745 if isinstance(uri, basestring):746 uri = [uri]7 unmodified lines754 755 auth_manager = AuthManager()756 757 773-758 class AuthObject(object):775- """The :class:`AuthObject` is a simple HTTP Authentication token. When776- given to a Requests function, it enables Basic HTTP Authentication for that777- Request. You can also enable Authorization for domain realms with AutoAuth.778- See AutoAuth for more details.759+ """The :class:`AuthObject` is a simple HTTP Authentication token.760 761+ When given to a Requests function, it enables Basic HTTP Authentication762+ for that Request. You can also enable Authorization for domain realms763+ with AutoAuth. See AutoAuth for more details.764+765 :param username: Username to authenticate with.766 :param password: Password for given username.767 :param realm: (optional) the realm this auth applies to768 :param handler: (optional) basic || digest || proxy_basic || proxy_digest19 unmodified linesmodified:requests/monkeys.py+4 added-10 removed
6 unmodified lines7 Urllib2 Monkey patches.8 9 """10 11-import urllib211 import re12+import urllib213 14+15 class Request(urllib2.Request):16 """Hidden wrapper around the urllib2.Request object. Allows for manual17 setting of HTTP methods.18 """16 unmodified lines35 36 http_error_302 = http_error_303 = http_error_307 = http_error_30137 38 38-39 class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):40 """HTTP Basic Auth Handler with authentication loop fixes."""41 42 def __init__(self, *args, **kwargs):43 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)44 self.retried_req = None45 self.retried = 046 47-47 def reset_retry_count(self):48 # Python 2.6.5 will call this on 401 or 407 errors and thus loop49 # forever. We disable reset_retry_count completely and reset in50 # http_error_auth_reqed instead.51 pass52 54-53 def http_error_auth_reqed(self, auth_header, host, req, headers):54 # Reset the retry counter once for each request.55 if req is not self.retried_req:56 self.retried_req = req3 unmodified lines60 self, auth_header, host, req, headers61 )62 63 66-64 class HTTPForcedBasicAuthHandler(HTTPBasicAuthHandler):65 """HTTP Basic Auth Handler with forced Authentication."""66 67 auth_header = 'Authorization'68 rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'69 'realm=(["\'])(.*?)\\2', re.I)70 74- def __init__(self, *args, **kwargs):71+ def __init__(self, *args, **kwargs):72 HTTPBasicAuthHandler.__init__(self, *args, **kwargs)73 77-74 def http_error_401(self, req, fp, code, msg, headers):75 url = req.get_full_url()76 response = self._http_error_auth_reqed('www-authenticate', url, req, headers)77 self.reset_retry_count()78 return response79 80 http_error_404 = http_error_40181 86-82 def _http_error_auth_reqed(self, authreq, host, req, headers):83 84 authreq = headers.get(authreq, None)85 24 unmodified lines110 self.retried = 0111 return response112 113 119-114 class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):115 116 def __init__(self, *args, **kwargs):117 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)20 unmodified lines138 except ValueError, inst:139 arg = inst.args[0]140 if arg.startswith("AbstractDigestAuthHandler doesn't know "):141 return148- raise142+ raisemodified:requests/sessions.py+1 added-5 removed
13 unmodified lines14 from . import api15 from .utils import add_dict_to_cookiejar16 17 18-18 class Session(object):19 """A Requests session."""20 21 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']22 24-23 def __init__(self, **kwargs):24 25 # Set up a CookieJar to be used by default26 self.cookies = cookielib.FileCookieJar()4 unmodified lines31 32 # Map and wrap requests.api methods33 self._map_api_methods()34 37-35 def __repr__(self):36 return '<requests-client at 0x%x>' % (id(self))37 38 def __enter__(self):2 unmodified lines41 def __exit__(self, *args):42 # print args43 pass44 48-45 def _map_api_methods(self):46 """Reads each available method from requests.api and decorates47 them with a wrapper, which inserts any instance-local attributes48 (from __attrs__) that have been set, combining them with **kwargs.27 unmodified lines76 77 def session(**kwargs):78 """Returns a :class:`Session` for context-managment."""79 84- return Session(**kwargs)80+ return Session(**kwargs)modified:requests/status_codes.py+1 added-1 removed
78 unmodified lines79 for (code, titles) in _codes.items():80 for title in titles:81 setattr(codes, title, code)82 if not title.startswith('\\'):83- setattr(codes, title.upper(), code)83+ setattr(codes, title.upper(), code)modified:requests/structures.py+3 added-1 removed
6 unmodified lines7 Datastructures that power Requests.8 9 """10 11+12 class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary14 15 For example, ``headers['content-encoding']`` will return the30 unmodified lines46 return self[key]47 else:48 return default49 50+51 class LookupDict(dict):52 """Dictionary lookup object."""53 54 def __init__(self, name=None):8 unmodified lines63 64 return self.__dict__.get(key, None)65 66 def get(self, key, default=None):65- return self.__dict__.get(key, default)67+ return self.__dict__.get(key, default)modified:requests/utils.py+13 added-10 removed
49 unmodified lines50 if len(params):51 52 collector.append('; '.join(_params))53 54- if not len(headers) == i+1:54+ if not len(headers) == i + 1:55 collector.append(', ')56 57-57 # Remove trailing seperators.58 if collector[-1] in (', ', '; '):59 del collector[-1]60 61 return ''.join(collector)62 63 65-64 def dict_from_cookiejar(cj):65 """Returns a key/value dictionary from a CookieJar.66 67 :param cj: CookieJar object to extract cookies from.110 unmodified lines178 179 def stream_decode_response_unicode(iterator, r):180 """Stream decodes a iterator."""181 encoding = get_encoding_from_headers(r.headers)184- if encoding is None:182+ try:183+ decoder = codecs.getincrementaldecoder(str(encoding))(errors='replace')184+ except LookupError:185 for item in iterator:186 yield item187 return188-189- decoder = codecs.getincrementaldecoder(encoding)(errors='replace')188 for chunk in iterator:189 rv = decoder.decode(chunk)190 if rv:191 yield rv26 unmodified lines218 try:219 return unicode(r.content, encoding)220 except UnicodeError:221 tried_encodings.append(encoding)222+ except LookupError:223+ return r.content224 225 # Fall back:226 try:227 return unicode(r.content, encoding, errors='replace')6 unmodified lines234 235 :param content: bytestring to gzip-decode.236 """237 238- return zlib.decompress(content, 16+zlib.MAX_WBITS)239- return zlib.decompress(content, 16+zlib.MAX_WBITS)238 return zlib.decompress(content, 16 + zlib.MAX_WBITS)239+ return zlib.decompress(content, 16 + zlib.MAX_WBITS)240+ return zlib.decompress(content, 16 + zlib.MAX_WBITS)241 242 243 def stream_decode_gzip(iterator):244 """Stream decodes a gzip-encoded iterator"""9 unmodified lines254 yield rv255 except zlib.error:256 pass257 258+259 def curl_from_request(request):260 """Returns a curl command from the request.261 262 :param request: The :class:`Request <Request>` object13 unmodified lines276 277 #: -u/--user - Specify the user name and password to use for server auth.278 #: Basic Auth only for now279 auth = ''280+281 if request.auth is not None:280- auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)282 283+ auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)284+285 method = ''286+287 if request.method.upper() == 'HEAD':288 #: -I/--head - fetch headers only.289 method = '-I '290 else:33 unmodified lines324 form = "-d '%s' " % (request._enc_data)325 326 #: Params handled in _build_url327 return curl + auth + method + header + cookies + form + '"' + request._build_url() + '"'324-modified:AUTHORS+2 added-1 removed
47 unmodified lines48 - Alejandro Giacometti49 - Rick Mak50 - Johan Bergström51 - Josselin Jacquard52+- Michael Van Veen <michael@mvanveen.net>53 - Mike Waldner53-- Serge Domkowski54+- Serge Domkowski