added toa AUTHORS file
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michael Van Veen · committed by Michael Van Veen · parent 784b671 · Browse files · 11 files·+74 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+74 added−80 removed
- other:+74 added−80 removed
Provenance
- Commit
5345a89- Tree
d11914f- Author
Michael Van Veen <michael@mvanveen.net>- Committer
Michael Van Veen <michael@mvanveen.net>- Parent
784b671
11 files changed+74 added−80 removed
modified:requests/api.py+11 added-11 removed
52 unmodified lines53 for k, v in headers.items() or {}:54 headers[k] = header_expand(v)55 56 args = dict(57- method = method,58- url = url,59- data = data,60- params = params,61- headers = headers,62- cookiejar = cookies,63- files = files,64- auth = auth,65- timeout = timeout or config.settings.timeout,66- allow_redirects = allow_redirects,67- proxies = proxies or config.settings.proxies,57+ method=method,58+ url=url,59+ data=data,60+ params=params,61+ headers=headers,62+ cookiejar=cookies,63+ files=files,64+ auth=auth,65+ timeout=timeout or config.settings.timeout,66+ allow_redirects=allow_redirects,67+ proxies=proxies or config.settings.proxies,68 )69 70 # Arguments manipulation hook.71 args = dispatch_hook('args', hooks, args)85 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+1 added-1 removed
24 unmodified lines25 from sessions import session26 from status_codes import codes27 from config import settings28 29-import utils29+import utilsmodified:requests/exceptions.py+7 added-1 removed
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+15 class AuthenticationError(RequestException):16 """The authentication credentials provided were invalid."""15- 17+18+19 class Timeout(RequestException):20 """The request timed out."""21 22+23 class URLRequired(RequestException):24 """A valid URL is required to make a request."""25 26+27 class InvalidMethod(RequestException):28 """An inappropriate method was attempted."""29 30+31 class TooManyRedirects(RequestException):32 """Too many redirects."""modified:requests/models.py+21 added-42 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, 'code', None)5 unmodified lines185 if self.cookiejar:186 187 response.cookies = dict_from_cookiejar(self.cookiejar)188 196-189 except AttributeError:190 pass191 192 if is_error:2 unmodified lines195 response.url = getattr(resp, 'url', None)196 197 return response198 207-199 history = []200 201 r = build(resp)202 45 unmodified lines248 249 self.response = r250 self.response.request = self251 261-252 @staticmethod253 def _encode_params(data):254 """Encode parameters in a piece of data.255 9 unmodified lines265 result = []266 for k, vs in data.items():267 for v in isinstance(vs, list) and vs or [vs]:268 result.append((k.encode('utf-8') if isinstance(k, unicode) else k,279- v.encode('utf-8') if isinstance(v, unicode) else v))280- return result, urllib.urlencode(result, doseq=True)269+ v.encode('utf-8') if isinstance(v, unicode) else v)270+ )271+ return (result, urllib.urlencode(result, doseq=True))272+273 else:274 return data, data275 284-276 def _build_url(self):277 """Build the actual URL to use."""278 279 # Support for unicode domain names and paths.280 scheme, netloc, path, params, query, fragment = urlparse(self.url)281 netloc = netloc.encode('idna')282+283 if isinstance(path, unicode):284 path = path.encode('utf-8')285+286 path = urllib.quote(path, safe="%/:=&?~#+!$,;'@()*[]")294- self.url = str(urlunparse([ scheme, netloc, path, params, query, fragment ]))287 288+ self.url = str(urlunparse(289+ [scheme, netloc, path, params, query, fragment]290+ ))291+292 if self._enc_params:293 if urlparse(self.url).query:294 return '%s&%s' % (self.url, self._enc_params)295 else:296 return '%s?%s' % (self.url, self._enc_params)297 else:298 return self.url299 304-300 def send(self, anyway=False):301 """Sends the request. Returns True of successful, false if not.302 If there was an HTTPError during transmission,303 self.response.status_code will contain the HTTPError code.11 unmodified lines315 settings.verbose.write('%s %s %s\n' % (316 datetime.now().isoformat(), self.method, self.url317 ))318 324-319 url = self._build_url()320 if self.method in ('GET', 'HEAD', 'DELETE'):321 req = _Request(url, method=self.method)322 else:10 unmodified lines333 else:334 req = _Request(url, data=self._enc_data, method=self.method)335 336 if self.headers:343- for k,v in self.headers.iteritems():337+ for k, v in self.headers.iteritems():338 req.add_header(k, v)339 340 if not self.sent or anyway:341 32 unmodified lines374 else:375 self._build_response(resp)376 self.response.ok = True377 384-378 self.sent = self.response.ok379 380 return self.sent381 382 383 class Response(object):391- """The core :class:`Response <Response>` object. All392- :class:`Request <Request>` objects contain a393- :class:`response <Response>` attribute, which is an instance394- of this class.384+ """The core :class:`Response <Response>` object.385+386+387+ All :class:`Request <Request>` objects contain a :class:`response388+ <Response>` attribute, which is an instance of this class.389 """390 391 def __init__(self):392 30 unmodified lines423 424 #: A dictionary of Cookies the server sent back.425 self.cookies = None426 433-427 def __repr__(self):428 return '<Response [%s]>' % (self.status_code)429 437-430 def __nonzero__(self):431 """Returns true if :attr:`status_code` is 'OK'."""432 433 return not self.error53 unmodified lines487 488 self._content_consumed = True489 return self._content490 499-491 def raise_for_status(self):492 """Raises stored :class:`HTTPError` or :class:`URLError`, if one occured."""493 if self.error:494 raise self.error495 496 506-497 class AuthManager(object):498 """Requests Authentication Manager."""499 500 def __new__(cls):4 unmodified lines505 cls.__singleton__ = singleton = object.__new__(cls)506 507 return singleton508 519-509 def __init__(self):510 self.passwd = {}511 self._auth = {}512 524-513 def __repr__(self):514 return '<AuthManager [%s]>' % (self.method)515 528-516 def add_auth(self, uri, auth):517 """Registers AuthObject to AuthManager."""518 519 uri = self.reduce_uri(uri, False)6 unmodified lines526 pass527 528 self._auth[uri] = auth529 543-530 def add_password(self, realm, uri, user, passwd):531 """Adds password to AuthManager."""532 # uri could be a single URI or a sequence533 if isinstance(uri, basestring):4 unmodified lines538 if reduced_uri not in self.passwd:539 self.passwd[reduced_uri] = {}540 self.passwd[reduced_uri] = (user, passwd)541 556-542 def find_user_password(self, realm, authuri):543 for uris, authinfo in self.passwd.iteritems():544 reduced_authuri = self.reduce_uri(authuri, False)545 for uri in uris:1 unmodified line547 return authinfo548 549 return (None, None)550 566-551 def get_auth(self, uri):552 (in_domain, in_path) = self.reduce_uri(uri, False)553 554 for domain, path, authority in (2 unmodified lines557 if in_domain == domain:558 if path in in_path:559 return authority560 577-561 def reduce_uri(self, uri, default_port=True):562 """Accept authority or URI and extract only the authority and path."""563 564 # note HTTP URLs do not have a userinfo component20 unmodified lines585 authority = "%s:%d" % (host, dport)586 587 return authority, path588 606-589 def is_suburi(self, base, test):590 """Check if test is below base in a URI tree591 592 Both args must be URIs in reduced form.6 unmodified lines599 if len(common) == len(base[1]):600 return True601 return False602 621-603 def empty(self):604 self.passwd = {}605 625-606 def remove(self, uri, realm=None):607 # uri could be a single URI or a sequence608 if isinstance(uri, basestring):609 uri = [uri]1 unmodified line611 for default_port in True, False:612 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])613 del self.passwd[reduced_uri][realm]614 635-615 def __contains__(self, uri):616 # uri could be a single URI or a sequence617 if isinstance(uri, basestring):618 uri = [uri]7 unmodified lines626 627 auth_manager = AuthManager()628 629 651-630 class AuthObject(object):653- """The :class:`AuthObject` is a simple HTTP Authentication token. When654- given to a Requests function, it enables Basic HTTP Authentication for that655- Request. You can also enable Authorization for domain realms with AutoAuth.656- See AutoAuth for more details.631+ """The :class:`AuthObject` is a simple HTTP Authentication token.632 633+ When given to a Requests function, it enables Basic HTTP Authentication634+ for that Request. You can also enable Authorization for domain realms635+ with AutoAuth. See AutoAuth for more details.636+637 :param username: Username to authenticate with.638 :param password: Password for given username.639 :param realm: (optional) the realm this auth applies to640 :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+8 added-7 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.164 unmodified lines232 233 :param content: bytestring to gzip-decode.234 """235 238- return zlib.decompress(content, 16+zlib.MAX_WBITS)239- return zlib.decompress(content, 16+zlib.MAX_WBITS)236 return zlib.decompress(content, 16 + zlib.MAX_WBITS)237+ return zlib.decompress(content, 16 + zlib.MAX_WBITS)238+ return zlib.decompress(content, 16 + zlib.MAX_WBITS)239 240 241 def stream_decode_gzip(iterator):242 """Stream decodes a gzip-encoded iterator"""9 unmodified lines252 yield rv253 except zlib.error:254 pass255 256+257 def curl_from_request(request):258 """Returns a curl command from the request.259 260 :param request: The :class:`Request <Request>` object13 unmodified lines274 275 #: -u/--user - Specify the user name and password to use for server auth.276 #: Basic Auth only for now277 auth = ''278+279 if request.auth is not None:280- auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)280 281+ auth = '-u "%s:%s" ' % (request.auth.username, request.auth.password)282+283 method = ''284+285 if request.method.upper() == 'HEAD':286 #: -I/--head - fetch headers only.287 method = '-I '288 else:33 unmodified lines322 form = "-d '%s' " % (request._enc_data)323 324 #: Params handled in _build_url325 return curl + auth + method + header + cookies + form + '"' + request._build_url() + '"'324-modified:AUTHORS+2 added-1 removed
41 unmodified lines42 - Alejandro Giacometti43 - Rick Mak44 - Johan Bergström45 - Josselin Jacquard46+- Michael Van Veen <michael@mvanveen.net>47 - Mike Waldner47-- Serge Domkowski48+- Serge Domkowski