Skip to content
Myr

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

12 files+108 added−71 removed

modified:docs/index.rst+2 added-1 removed
39 unmodified lines
40------------4142`Twitter, Inc <http://twitter.com>`_,43a U.S. Federal Institution,44and `Readability <http://readability.com>`_44`Readability <http://readability.com>`_, and45`Work for Pie <http://workforpie.com>`_46use Requests internally.4748**Daniel Greenfeld**49 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to
67 unmodified lines
modified:requests/api.py+22 added
64 unmodified lines
65 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 )9394 # Arguments manipulation hook.95 args = dispatch_hook('args', hooks, args)
86 unmodified lines
modified:requests/config.py+15 added
4 unmodified lines
5~~~~~~~~~~~~~~~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__()
17 unmodified lines
modified:requests/core.py+3 added-3 removed
17 unmodified lines
18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'202122from models import HTTPError, Request, Response22from api import *23from config import settings24from exceptions import *25from models import HTTPError, Request, Response26from sessions import session27from status_codes import codes27from config import settings2829import utils29import utils
modified:requests/exceptions.py+18 added
4 unmodified lines
5~~~~~~~~~~~~~~~67"""8910class RequestException(Exception):11 """There was an ambiguous exception that occured while handling your12 request."""1314class AuthenticationError(RequestException):15 """The authentication credentials provided were invalid."""16 1718class AuthenticationError(RequestException):19 """The authentication credentials provided were invalid."""202122class Timeout(RequestException):23 """The request timed out."""242526class 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."""353637class TooManyRedirects(RequestException):38 """Too many redirects."""
modified:requests/models.py+24 added-39 removed
28 unmodified lines
2930REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)31323333class 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 lines
9495 #: True if Request has been sent.96 self.sent = False979998 # Header manipulation and defaults.99100 if settings.accept_gzip:101 settings.base_headers.update({'Accept-Encoding': 'gzip'})
8 unmodified lines
110 headers[k] = v111112 self.headers = headers113116114 def __repr__(self):115 return '<Request [%s]>' % (self.method)116120117 def _checks(self):118 """Deterministic checks for consistency."""119120 if not self.url:121 raise URLRequired122127123 def _get_opener(self):124 """Creates appropriate opener object for urllib2."""125126 _handlers = []
40 unmodified lines
167 opener.addheaders.remove((key, val))168169 return opener.open170176171 def _build_response(self, resp, is_error=False):172 """Build internal :class:`Response <Response>` object173 from given response.174 """175182176 def build(resp):177178 response = Response()179 response.status_code = getattr(resp, 'status', None)
3 unmodified lines
183 response.raw = resp._raw184185 # if self.cookiejar:186187 response.cookies = dict_from_cookiejar(self.cookiejar)188189190 # response.cookies = dict_from_cookiejar(self.cookiejar)191192 response.cookies = dict_from_cookiejar(self.cookiejar)193194 except AttributeError:195 pass196197 if is_error:198 response.error = resp199200 return response201204202 # Request collector.203 history = []204205 # Create the lone response object.
70 unmodified lines
276277 # Give Response some context.278 self.response.request = self279283280 @staticmethod281 def _encode_params(data):282 """Encode parameters in a piece of data.283
9 unmodified lines
293 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))300301 else:302 return data, data303306304 def _build_url(self):305 """Build the actual URL to use."""306307 # Support for unicode domain names and paths.
10 unmodified lines
318 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")319320 # 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 ))325326 # Query Parameters?327 if self._enc_params:328
8 unmodified lines
337 else:338 # Kosher URL.339 return self.url340341341 def send(self, connection=None, anyway=False):342 """Sends the shit."""343344 # Safety check.
85 unmodified lines
430 settings.verbose.write('%s %s %s\n' % (431 datetime.now().isoformat(), self.method, self.url432 ))433435434 url = self._build_url()435 if self.method in ('GET', 'HEAD', 'DELETE'):436 req = _Request(url, method=self.method)437 else:
10 unmodified lines
448 else:449 req = _Request(url, data=self._enc_data, method=self.method)450451 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)454455 if not self.sent or anyway:456
32 unmodified lines
489 else:490 self._build_response(resp)491 self.response.ok = True492495493 self.sent = self.response.ok494495 return self.sent496497498class 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.500501502 All :class:`Request <Request>` objects contain a :class:`response503 <Response>` attribute, which is an instance of this class.504 """505506 def __init__(self):507
27 unmodified lines
535536 #: A dictionary of Cookies the server sent back.537 self.cookies = None538541539 def __repr__(self):540 return '<Response [%s]>' % (self.status_code)541545542 def __nonzero__(self):543 """Returns true if :attr:`status_code` is 'OK'."""544545 return not self.error
56 unmodified lines
602603 self._content_consumed = True604 return self._content605610606 def raise_for_status(self):607 """Raises stored :class:`HTTPError` or :class:`URLError`,608 if one occured.609 """
3 unmodified lines
613614 if (self.status_code >= 300) and (self.status_code < 400):615 raise Exception('300 yo')616617618 elif (self.status_code >= 400) and (self.status_code < 500):619 raise Exception('400 yo')620621 elif (self.status_code >= 500) and (self.status_code < 600):
11 unmodified lines
633 cls.__singleton__ = singleton = object.__new__(cls)634635 return singleton636641637 def __init__(self):638 self.passwd = {}639 self._auth = {}640646641 def __repr__(self):642 return '<AuthManager [%s]>' % (self.method)643650644 def add_auth(self, uri, auth):645 """Registers AuthObject to AuthManager."""646647 uri = self.reduce_uri(uri, False)
6 unmodified lines
654 pass655656 self._auth[uri] = auth657665658 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 lines
666 if reduced_uri not in self.passwd:667 self.passwd[reduced_uri] = {}668 self.passwd[reduced_uri] = (user, passwd)669678670 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 line
675 return authinfo676677 return (None, None)678688679 def get_auth(self, uri):680 (in_domain, in_path) = self.reduce_uri(uri, False)681682 for domain, path, authority in (
2 unmodified lines
685 if in_domain == domain:686 if path in in_path:687 return authority688699689 def reduce_uri(self, uri, default_port=True):690 """Accept authority or URI and extract only the authority and path."""691692 # note HTTP URLs do not have a userinfo component
20 unmodified lines
713 authority = "%s:%d" % (host, dport)714715 return authority, path716728717 def is_suburi(self, base, test):718 """Check if test is below base in a URI tree719720 Both args must be URIs in reduced form.
6 unmodified lines
727 if len(common) == len(base[1]):728 return True729 return False730743731 def empty(self):732 self.passwd = {}733747734 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 line
739 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]742757743 def __contains__(self, uri):744 # uri could be a single URI or a sequence745 if isinstance(uri, basestring):746 uri = [uri]
7 unmodified lines
754755auth_manager = AuthManager()756757773758class 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.760761 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.764765 :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_digest
19 unmodified lines
modified:requests/monkeys.py+4 added-10 removed
6 unmodified lines
7Urllib2 Monkey patches.89"""1011import urllib211import re12import urllib2131415class Request(urllib2.Request):16 """Hidden wrapper around the urllib2.Request object. Allows for manual17 setting of HTTP methods.18 """
16 unmodified lines
3536 http_error_302 = http_error_303 = http_error_307 = http_error_30137383839class 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 = 0464747 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 pass525453 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 = req
3 unmodified lines
60 self, auth_header, host, req, headers61 )62636664class 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)7074 def __init__(self, *args, **kwargs):71 def __init__(self, *args, **kwargs):72 HTTPBasicAuthHandler.__init__(self, *args, **kwargs)737774 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_401818682 def _http_error_auth_reqed(self, authreq, host, req, headers):8384 authreq = headers.get(authreq, None)85
24 unmodified lines
110 self.retried = 0111 return response112113119114class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):115116 def __init__(self, *args, **kwargs):117 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)
20 unmodified lines
138 except ValueError, inst:139 arg = inst.args[0]140 if arg.startswith("AbstractDigestAuthHandler doesn't know "):141 return148 raise142 raise
modified:requests/sessions.py+1 added-5 removed
13 unmodified lines
14from . import api15from .utils import add_dict_to_cookiejar16171818class Session(object):19 """A Requests session."""2021 __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks']222423 def __init__(self, **kwargs):2425 # Set up a CookieJar to be used by default26 self.cookies = cookielib.FileCookieJar()
4 unmodified lines
3132 # Map and wrap requests.api methods33 self._map_api_methods()343735 def __repr__(self):36 return '<requests-client at 0x%x>' % (id(self))3738 def __enter__(self):
2 unmodified lines
41 def __exit__(self, *args):42 # print args43 pass444845 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 lines
7677def session(**kwargs):78 """Returns a :class:`Session` for context-managment."""7984 return Session(**kwargs)80 return Session(**kwargs)
modified:requests/status_codes.py+1 added-1 removed
78 unmodified lines
79for (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 lines
7Datastructures that power Requests.89"""101112class CaseInsensitiveDict(dict):13 """Case-insensitive Dictionary1415 For example, ``headers['content-encoding']`` will return the
30 unmodified lines
46 return self[key]47 else:48 return default495051class LookupDict(dict):52 """Dictionary lookup object."""5354 def __init__(self, name=None):
8 unmodified lines
6364 return self.__dict__.get(key, None)6566 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 lines
50 if len(params):5152 collector.append('; '.join(_params))5354 if not len(headers) == i+1:54 if not len(headers) == i + 1:55 collector.append(', ')565757 # Remove trailing seperators.58 if collector[-1] in (', ', '; '):59 del collector[-1]6061 return ''.join(collector)62636564def dict_from_cookiejar(cj):65 """Returns a key/value dictionary from a CookieJar.6667 :param cj: CookieJar object to extract cookies from.
110 unmodified lines
178179def 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 return188189 decoder = codecs.getincrementaldecoder(encoding)(errors='replace')188 for chunk in iterator:189 rv = decoder.decode(chunk)190 if rv:191 yield rv
26 unmodified lines
218 try:219 return unicode(r.content, encoding)220 except UnicodeError:221 tried_encodings.append(encoding)222 except LookupError:223 return r.content224225 # Fall back:226 try:227 return unicode(r.content, encoding, errors='replace')
6 unmodified lines
234235 :param content: bytestring to gzip-decode.236 """237238 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)241242243def stream_decode_gzip(iterator):244 """Stream decodes a gzip-encoded iterator"""
9 unmodified lines
254 yield rv255 except zlib.error:256 pass257258259def curl_from_request(request):260 """Returns a curl command from the request.261262 :param request: The :class:`Request <Request>` object
13 unmodified lines
276277 #: -u/--user - Specify the user name and password to use for server auth.278 #: Basic Auth only for now279 auth = ''280281 if request.auth is not None:280 auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)282283 auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)284285 method = ''286287 if request.method.upper() == 'HEAD':288 #: -I/--head - fetch headers only.289 method = '-I '290 else:
33 unmodified lines
324 form = "-d '%s' " % (request._enc_data)325326 #: Params handled in _build_url327 return curl + auth + method + header + cookies + form + '"' + request._build_url() + '"'324
modified:AUTHORS+2 added-1 removed
47 unmodified lines
48- Alejandro Giacometti49- Rick Mak50- Johan Bergström51- Josselin Jacquard52- Michael Van Veen <michael@mvanveen.net>53- Mike Waldner53- Serge Domkowski54- Serge Domkowski