Skip to content
Myr

package refactor

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Kenneth Reitz · committed by Kenneth Reitz · parent 1421ffa · Browse files · 6 files+649 added−576 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+649 added−576 removed

  • other:+649 added−576 removed

6 files+649 added−576 removed

added:requests/api.py+115 added
1# -*- coding: utf-8 -*-23"""4requests.api5~~~~~~~~~~~~67This module impliments the Requests API.89:copyright: (c) 2011 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1314import requests15from .models import Request, Response, AuthManager, AuthObject, auth_manager161718__all__ = ('request', 'get', 'head', 'post', 'put', 'delete')19202122def request(method, url, **kwargs):23 """Sends a `method` request. Returns :class:`Response` object.2425 :param method: method for the new :class:`Request` object.26 :param url: URL for the new :class:`Request` object.27 :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.28 :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.29 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.30 :param cookies: (optional) CookieJar object to send with the :class:`Request`.31 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.32 :param auth: (optional) AuthObject to enable Basic HTTP Auth.33 :param timeout: (optional) Float describing the timeout of the request.34 """35 data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())3637 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),38 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),39 auth=kwargs.pop('auth', auth_manager.get_auth(url)),40 timeout=kwargs.pop('timeout', requests.timeout))41 r.send()4243 return r.response444546def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):47 """Sends a GET request. Returns :class:`Response` object.4849 :param url: URL for the new :class:`Request` object.50 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.51 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.52 :param cookies: (optional) CookieJar object to send with the :class:`Request`.53 :param auth: (optional) AuthObject to enable Basic HTTP Auth.54 :param timeout: (optional) Float describing the timeout of the request.55 """5657 return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)585960def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):61 """Sends a HEAD request. Returns :class:`Response` object.6263 :param url: URL for the new :class:`Request` object.64 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.65 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.66 :param cookies: (optional) CookieJar object to send with the :class:`Request`.67 :param auth: (optional) AuthObject to enable Basic HTTP Auth.68 :param timeout: (optional) Float describing the timeout of the request.69 """7071 return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)727374def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):75 """Sends a POST request. Returns :class:`Response` object.7677 :param url: URL for the new :class:`Request` object.78 :param data: (optional) Dictionary of POST data to send with the :class:`Request`.79 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.80 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.81 :param cookies: (optional) CookieJar object to send with the :class:`Request`.82 :param auth: (optional) AuthObject to enable Basic HTTP Auth.83 :param timeout: (optional) Float describing the timeout of the request.84 """8586 return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)878889def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):90 """Sends a PUT request. Returns :class:`Response` object.9192 :param url: URL for the new :class:`Request` object.93 :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.94 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.95 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.96 :param cookies: (optional) CookieJar object to send with the :class:`Request`.97 :param auth: (optional) AuthObject to enable Basic HTTP Auth.98 :param timeout: (optional) Float describing the timeout of the request.99 """100101 return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)102103104def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):105 """Sends a DELETE request. Returns :class:`Response` object.106107 :param url: URL for the new :class:`Request` object.108 :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.109 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.110 :param cookies: (optional) CookieJar object to send with the :class:`Request`.111 :param auth: (optional) AuthObject to enable Basic HTTP Auth.112 :param timeout: (optional) Float describing the timeout of the request.113 """114115 return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)
modified:requests/core.py+8 added-575 removed
1# -*- coding: utf-8 -*-23"""4 requests.core5 ~~~~~~~~~~~~~4requests.core5~~~~~~~~~~~~~67 This module implements the main Requests system.7This module implements the main Requests system.89 :copyright: (c) 2011 by Kenneth Reitz.10 :license: ISC, see LICENSE for more details.9:copyright: (c) 2011 by Kenneth Reitz.10:license: ISC, see LICENSE for more details.1112"""1313from __future__ import absolute_import1415import requests16import urllib17import urllib218import socket19import zlib2021from urllib2 import HTTPError22from urlparse import urlparse2324from .packages.poster.encode import multipart_encode25from .packages.poster.streaminghttp import register_openers, get_handlers262714__title__ = 'requests'15__version__ = '0.3.3'16__build__ = 0x00030317__author__ = 'Kenneth Reitz'18__license__ = 'ISC'19__copyright__ = 'Copyright 2011 Kenneth Reitz'2035__all__ = [36 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete',37 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError',38 'URLRequired', 'InvalidMethod', 'HTTPError'39]214142class _Request(urllib2.Request):43 """Hidden wrapper around the urllib2.Request object. Allows for manual44 setting of HTTP methods.45 """4647 def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):48 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)49 self.method = method5051 def get_method(self):52 if self.method:53 return self.method5455 return urllib2.Request.get_method(self)565758class _HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):59 # from mercurial6061 def __init__(self, *args, **kwargs):62 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)63 self.retried_req = None6465 def reset_retry_count(self):66 # Python 2.6.5 will call this on 401 or 407 errors and thus loop67 # forever. We disable reset_retry_count completely and reset in68 # http_error_auth_reqed instead.69 pass7071 def http_error_auth_reqed(self, auth_header, host, req, headers):72 # Reset the retry counter once for each request.73 if req is not self.retried_req:74 self.retried_req = req75 self.retried = 076 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(77 self, auth_header, host, req, headers)787980class Request(object):81 """The :class:`Request` object. It carries out all functionality of82 Requests. Recommended interface is with the Requests functions.83 """8485 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')8687 def __init__(self, url=None, headers=dict(), files=None, method=None,88 data=dict(), auth=None, cookiejar=None, timeout=None):8990 socket.setdefaulttimeout(timeout)9192 self.url = url93 self.headers = headers94 self.files = files95 self.method = method96 self.data = {}9798 # self.data = {}99 if hasattr(data, 'items'):100 for (k, v) in data.items():101 self.data.update({102 k.encode('utf-8') if isinstance(k, unicode) else k:103 v.encode('utf-8') if isinstance(v, unicode) else v104 })105106 # url encode data if it's a dict107 if hasattr(data, 'items'):108 self._enc_data = urllib.urlencode(self.data)109 else:110 self._enc_data = data111112113 self.response = Response()114115 if isinstance(auth, (list, tuple)):116 auth = AuthObject(*auth)117 if not auth:118 auth = auth_manager.get_auth(self.url)119 self.auth = auth120 self.cookiejar = cookiejar121 self.sent = False122123124 def __repr__(self):125 return '<Request [%s]>' % (self.method)126127128 def __setattr__(self, name, value):129 if (name == 'method') and (value):130 if not value in self._METHODS:131 raise InvalidMethod()132133 object.__setattr__(self, name, value)134135136 def _checks(self):137 """Deterministic checks for consistency."""138139 if not self.url:140 raise URLRequired141142143 def _get_opener(self):144 """Creates appropriate opener object for urllib2."""145146 _handlers = []147148 if self.cookiejar is not None:149 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))150151 if self.auth:152 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):153 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)154 self.auth.handler = self.auth.handler(auth_manager)155 auth_manager.add_auth(self.url, self.auth)156157 _handlers.append(self.auth.handler)158159 if not _handlers:160 return urllib2.urlopen161162 _handlers.extend(get_handlers())163 opener = urllib2.build_opener(*_handlers)164165 if self.headers:166 # Allow default headers in the opener to be overloaded167 normal_keys = [k.capitalize() for k in self.headers]168 for key, val in opener.addheaders[:]:169 if key not in normal_keys:170 continue171 # Remove it, we have a value to take its place172 opener.addheaders.remove((key, val))173174 return opener.open175176 def _build_response(self, resp):177 """Build internal Response object from given response."""178 if isinstance(resp, HTTPError):179 # print resp.__dict__180 pass181182 self.response.status_code = getattr(resp, 'code', None)183184 try:185 self.response.headers = getattr(resp.info(), 'dict', None)186 self.response.content = resp.read()187 except AttributeError, why:188 pass189190 if self.response.headers.get('content-encoding', None) == 'gzip':191 try:192 self.response.content = zlib.decompress(self.response.content, 16+zlib.MAX_WBITS)193 except zlib.error:194 pass195196 self.response.url = getattr(resp, 'url', None)197198199 @staticmethod200 def _build_url(url, data=None):201 """Build URLs."""202203 if urlparse(url).query:204 return '%s&%s' % (url, data)205 else:206 if data:207 return '%s?%s' % (url, data)208 else:209 return url210211212 def send(self, anyway=False):213 """Sends the request. Returns True of successful, false if not.214 If there was an HTTPError during transmission,215 self.response.status_code will contain the HTTPError code.216217 Once a request is successfully sent, `sent` will equal True.218219 :param anyway: If True, request will be sent, even if it has220 already been sent.221 """222 self._checks()223 success = False224225 if self.method in ('GET', 'HEAD', 'DELETE'):226 req = _Request(self._build_url(self.url, self._enc_data), method=self.method)227 else:228229 if self.files:230 register_openers()231232 if self.data:233 self.files.update(self.data)234235 datagen, headers = multipart_encode(self.files)236 req = _Request(self.url, data=datagen, headers=headers, method=self.method)237238 else:239 req = _Request(self.url, data=self._enc_data, method=self.method)240241 if self.headers:242 req.headers.update(self.headers)243244 if not self.sent or anyway:245246 try:247 opener = self._get_opener()248 resp = opener(req)249250 if self.cookiejar is not None:251 self.cookiejar.extract_cookies(resp, req)252253 except urllib2.HTTPError, why:254 self._build_response(why)255 self.response.error = why256 else:257 self._build_response(resp)258 self.response.ok = True259260 self.response.cached = False261 else:262 self.response.cached = True263264 self.sent = self.response.ok265266 return self.sent267268269 def read(self, *args):270 return self.response.read()271272273274class Response(object):275 """The :class:`Request` object. All :class:`Request` objects contain a276 :class:`Request.response <response>` attribute, which is an instance of277 this class.278 """279280 def __init__(self):281 self.content = None282 self.status_code = None283 self.headers = dict()284 self.url = None285 self.ok = False286 self.error = None287 self.cached = False288289290 def __repr__(self):291 return '<Response [%s]>' % (self.status_code)292293294 def __nonzero__(self):295 """Returns true if status_code is 'OK'."""296 return not self.error297298299 def raise_for_status(self):300 """Raises stored HTTPError if one exists."""301 if self.error:302 raise self.error303304 def read(self, *args):305 return self.content306307308309class AuthManager(object):310 """Authentication Manager."""311312 def __new__(cls):313 singleton = cls.__dict__.get('__singleton__')314 if singleton is not None:315 return singleton316317 cls.__singleton__ = singleton = object.__new__(cls)318319 return singleton320321322 def __init__(self):323 self.passwd = {}324 self._auth = {}325326327 def __repr__(self):328 return '<AuthManager [%s]>' % (self.method)329330331 def add_auth(self, uri, auth):332 """Registers AuthObject to AuthManager."""333334 uri = self.reduce_uri(uri, False)335336 # try to make it an AuthObject337 if not isinstance(auth, AuthObject):338 try:339 auth = AuthObject(*auth)340 except TypeError:341 pass342343 self._auth[uri] = auth344345346 def add_password(self, realm, uri, user, passwd):347 """Adds password to AuthManager."""348 # uri could be a single URI or a sequence349 if isinstance(uri, basestring):350 uri = [uri]351352 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])353354 if reduced_uri not in self.passwd:355 self.passwd[reduced_uri] = {}356 self.passwd[reduced_uri] = (user, passwd)357358359 def find_user_password(self, realm, authuri):360 for uris, authinfo in self.passwd.iteritems():361 reduced_authuri = self.reduce_uri(authuri, False)362 for uri in uris:363 if self.is_suburi(uri, reduced_authuri):364 return authinfo365366 return (None, None)367368369 def get_auth(self, uri):370 (in_domain, in_path) = self.reduce_uri(uri, False)371372 for domain, path, authority in (373 (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()374 ):375 if in_domain == domain:376 if path in in_path:377 return authority378379380 def reduce_uri(self, uri, default_port=True):381 """Accept authority or URI and extract only the authority and path."""382 # note HTTP URLs do not have a userinfo component383 parts = urllib2.urlparse.urlsplit(uri)384 if parts[1]:385 # URI386 scheme = parts[0]387 authority = parts[1]388 path = parts[2] or '/'389 else:390 # host or host:port391 scheme = None392 authority = uri393 path = '/'394 host, port = urllib2.splitport(authority)395 if default_port and port is None and scheme is not None:396 dport = {"http": 80,397 "https": 443,398 }.get(scheme)399 if dport is not None:400 authority = "%s:%d" % (host, dport)401402 return authority, path403404405 def is_suburi(self, base, test):406 """Check if test is below base in a URI tree407408 Both args must be URIs in reduced form.409 """410 if base == test:411 return True412 if base[0] != test[0]:413 return False414 common = urllib2.posixpath.commonprefix((base[1], test[1]))415 if len(common) == len(base[1]):416 return True417 return False418419420 def empty(self):421 self.passwd = {}422423424 def remove(self, uri, realm=None):425 # uri could be a single URI or a sequence426 if isinstance(uri, basestring):427 uri = [uri]428429 for default_port in True, False:430 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])431 del self.passwd[reduced_uri][realm]432433434 def __contains__(self, uri):435 # uri could be a single URI or a sequence436 if isinstance(uri, basestring):437 uri = [uri]438439 uri = tuple([self.reduce_uri(u, False) for u in uri])440441 if uri in self.passwd:442 return True443444 return False445446auth_manager = AuthManager()447448449450class AuthObject(object):451 """The :class:`AuthObject` is a simple HTTP Authentication token. When452 given to a Requests function, it enables Basic HTTP Authentication for that453 Request. You can also enable Authorization for domain realms with AutoAuth.454 See AutoAuth for more details.455456 :param username: Username to authenticate with.457 :param password: Password for given username.458 :param realm: (optional) the realm this auth applies to459 :param handler: (optional) basic || digest || proxy_basic || proxy_digest460 """461462 _handlers = {463 'basic': _HTTPBasicAuthHandler,464 'digest': urllib2.HTTPDigestAuthHandler,465 'proxy_basic': urllib2.ProxyBasicAuthHandler,466 'proxy_digest': urllib2.ProxyDigestAuthHandler467 }468469 def __init__(self, username, password, handler='basic', realm=None):470 self.username = username471 self.password = password472 self.realm = realm473474 if isinstance(handler, basestring):475 self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)476 else:477 self.handler = handler478479480481482def request(method, url, **kwargs):483 """Sends a `method` request. Returns :class:`Response` object.484485 :param method: method for the new :class:`Request` object.486 :param url: URL for the new :class:`Request` object.487 :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.488 :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.489 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.490 :param cookies: (optional) CookieJar object to send with the :class:`Request`.491 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.492 :param auth: (optional) AuthObject to enable Basic HTTP Auth.493 :param timeout: (optional) Float describing the timeout of the request.494 """495 data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())496497 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),498 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),499 auth=kwargs.pop('auth', auth_manager.get_auth(url)),500 timeout=kwargs.pop('timeout', requests.timeout))501 r.send()502503 return r.response504505506def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):507 """Sends a GET request. Returns :class:`Response` object.508509 :param url: URL for the new :class:`Request` object.510 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.511 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.512 :param cookies: (optional) CookieJar object to send with the :class:`Request`.513 :param auth: (optional) AuthObject to enable Basic HTTP Auth.514 :param timeout: (optional) Float describing the timeout of the request.515 """516517 return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)518519520def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):521 """Sends a HEAD request. Returns :class:`Response` object.522523 :param url: URL for the new :class:`Request` object.524 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.525 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.526 :param cookies: (optional) CookieJar object to send with the :class:`Request`.527 :param auth: (optional) AuthObject to enable Basic HTTP Auth.528 :param timeout: (optional) Float describing the timeout of the request.529 """530531 return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)532533534def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):535 """Sends a POST request. Returns :class:`Response` object.536537 :param url: URL for the new :class:`Request` object.538 :param data: (optional) Dictionary of POST data to send with the :class:`Request`.539 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.540 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.541 :param cookies: (optional) CookieJar object to send with the :class:`Request`.542 :param auth: (optional) AuthObject to enable Basic HTTP Auth.543 :param timeout: (optional) Float describing the timeout of the request.544 """545546 return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)547548549def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):550 """Sends a PUT request. Returns :class:`Response` object.551552 :param url: URL for the new :class:`Request` object.553 :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.554 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.555 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.556 :param cookies: (optional) CookieJar object to send with the :class:`Request`.557 :param auth: (optional) AuthObject to enable Basic HTTP Auth.558 :param timeout: (optional) Float describing the timeout of the request.559 """560561 return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)562563564def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):565 """Sends a DELETE request. Returns :class:`Response` object.566567 :param url: URL for the new :class:`Request` object.568 :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.569 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.570 :param cookies: (optional) CookieJar object to send with the :class:`Request`.571 :param auth: (optional) AuthObject to enable Basic HTTP Auth.572 :param timeout: (optional) Float describing the timeout of the request.573 """574575 return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)576577578579class RequestException(Exception):580 """There was an ambiguous exception that occured while handling your581 request."""582583class AuthenticationError(RequestException):584 """The authentication credentials provided were invalid."""585586class URLRequired(RequestException):587 """A valid URL is required to make a request."""588589class InvalidMethod(RequestException):590 """An inappropriate method was attempted."""22from .models import HTTPError, auth_manager23from .api import *
added:requests/models.py+435 added
1# -*- coding: utf-8 -*-23"""4requests.system5~~~~~~~~~~~~~~~67"""89import requests10import urllib11import urllib212import socket13import zlib1415from urllib2 import HTTPError16from urlparse import urlparse1718from .monkeys import _Request, _HTTPBasicAuthHandler, _HTTPDigestAuthHandler1920from .packages.poster.encode import multipart_encode21from .packages.poster.streaminghttp import register_openers, get_handlers22232425class Request(object):26 """The :class:`Request` object. It carries out all functionality of27 Requests. Recommended interface is with the Requests functions.28 """2930 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')3132 def __init__(self, url=None, headers=dict(), files=None, method=None,33 data=dict(), auth=None, cookiejar=None, timeout=None):3435 socket.setdefaulttimeout(timeout)3637 self.url = url38 self.headers = headers39 self.files = files40 self.method = method41 self.data = {}4243 # self.data = {}44 if hasattr(data, 'items'):45 for (k, v) in data.items():46 self.data.update({47 k.encode('utf-8') if isinstance(k, unicode) else k:48 v.encode('utf-8') if isinstance(v, unicode) else v49 })5051 # url encode data if it's a dict52 if hasattr(data, 'items'):53 self._enc_data = urllib.urlencode(self.data)54 else:55 self._enc_data = data565758 self.response = Response()5960 if isinstance(auth, (list, tuple)):61 auth = AuthObject(*auth)62 if not auth:63 auth = auth_manager.get_auth(self.url)64 self.auth = auth65 self.cookiejar = cookiejar66 self.sent = False676869 def __repr__(self):70 return '<Request [%s]>' % (self.method)717273 def __setattr__(self, name, value):74 if (name == 'method') and (value):75 if not value in self._METHODS:76 raise InvalidMethod()7778 object.__setattr__(self, name, value)798081 def _checks(self):82 """Deterministic checks for consistency."""8384 if not self.url:85 raise URLRequired868788 def _get_opener(self):89 """Creates appropriate opener object for urllib2."""9091 _handlers = []9293 if self.cookiejar is not None:94 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))9596 if self.auth:97 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):98 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)99 self.auth.handler = self.auth.handler(auth_manager)100 auth_manager.add_auth(self.url, self.auth)101102 _handlers.append(self.auth.handler)103104 if not _handlers:105 return urllib2.urlopen106107 _handlers.extend(get_handlers())108 opener = urllib2.build_opener(*_handlers)109110 if self.headers:111 # Allow default headers in the opener to be overloaded112 normal_keys = [k.capitalize() for k in self.headers]113 for key, val in opener.addheaders[:]:114 if key not in normal_keys:115 continue116 # Remove it, we have a value to take its place117 opener.addheaders.remove((key, val))118119 return opener.open120121 def _build_response(self, resp):122 """Build internal Response object from given response."""123 if isinstance(resp, HTTPError):124 # print resp.__dict__125 pass126127 self.response.status_code = getattr(resp, 'code', None)128129 try:130 self.response.headers = getattr(resp.info(), 'dict', None)131 self.response.content = resp.read()132 except AttributeError, why:133 pass134135 if self.response.headers.get('content-encoding', None) == 'gzip':136 try:137 self.response.content = zlib.decompress(self.response.content, 16+zlib.MAX_WBITS)138 except zlib.error:139 pass140141 self.response.url = getattr(resp, 'url', None)142143144 @staticmethod145 def _build_url(url, data=None):146 """Build URLs."""147148 if urlparse(url).query:149 return '%s&%s' % (url, data)150 else:151 if data:152 return '%s?%s' % (url, data)153 else:154 return url155156157 def send(self, anyway=False):158 """Sends the request. Returns True of successful, false if not.159 If there was an HTTPError during transmission,160 self.response.status_code will contain the HTTPError code.161162 Once a request is successfully sent, `sent` will equal True.163164 :param anyway: If True, request will be sent, even if it has165 already been sent.166 """167 self._checks()168 success = False169170 if self.method in ('GET', 'HEAD', 'DELETE'):171 req = _Request(self._build_url(self.url, self._enc_data), method=self.method)172 else:173174 if self.files:175 register_openers()176177 if self.data:178 self.files.update(self.data)179180 datagen, headers = multipart_encode(self.files)181 req = _Request(self.url, data=datagen, headers=headers, method=self.method)182183 else:184 req = _Request(self.url, data=self._enc_data, method=self.method)185186 if self.headers:187 req.headers.update(self.headers)188189 if not self.sent or anyway:190191 try:192 opener = self._get_opener()193 resp = opener(req)194195 if self.cookiejar is not None:196 self.cookiejar.extract_cookies(resp, req)197198 except urllib2.HTTPError, why:199 self._build_response(why)200 self.response.error = why201 else:202 self._build_response(resp)203 self.response.ok = True204205 self.response.cached = False206 else:207 self.response.cached = True208209 self.sent = self.response.ok210211 return self.sent212213214 def read(self, *args):215 return self.response.read()216217218219class Response(object):220 """The :class:`Request` object. All :class:`Request` objects contain a221 :class:`Request.response <response>` attribute, which is an instance of222 this class.223 """224225 def __init__(self):226 self.content = None227 self.status_code = None228 self.headers = dict()229 self.url = None230 self.ok = False231 self.error = None232 self.cached = False233234235 def __repr__(self):236 return '<Response [%s]>' % (self.status_code)237238239 def __nonzero__(self):240 """Returns true if status_code is 'OK'."""241 return not self.error242243244 def raise_for_status(self):245 """Raises stored HTTPError if one exists."""246 if self.error:247 raise self.error248249 def read(self, *args):250 return self.content251252253254class AuthManager(object):255 """Authentication Manager."""256257 def __new__(cls):258 singleton = cls.__dict__.get('__singleton__')259 if singleton is not None:260 return singleton261262 cls.__singleton__ = singleton = object.__new__(cls)263264 return singleton265266267 def __init__(self):268 self.passwd = {}269 self._auth = {}270271272 def __repr__(self):273 return '<AuthManager [%s]>' % (self.method)274275276 def add_auth(self, uri, auth):277 """Registers AuthObject to AuthManager."""278279 uri = self.reduce_uri(uri, False)280281 # try to make it an AuthObject282 if not isinstance(auth, AuthObject):283 try:284 auth = AuthObject(*auth)285 except TypeError:286 pass287288 self._auth[uri] = auth289290291 def add_password(self, realm, uri, user, passwd):292 """Adds password to AuthManager."""293 # uri could be a single URI or a sequence294 if isinstance(uri, basestring):295 uri = [uri]296297 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])298299 if reduced_uri not in self.passwd:300 self.passwd[reduced_uri] = {}301 self.passwd[reduced_uri] = (user, passwd)302303304 def find_user_password(self, realm, authuri):305 for uris, authinfo in self.passwd.iteritems():306 reduced_authuri = self.reduce_uri(authuri, False)307 for uri in uris:308 if self.is_suburi(uri, reduced_authuri):309 return authinfo310311 return (None, None)312313314 def get_auth(self, uri):315 (in_domain, in_path) = self.reduce_uri(uri, False)316317 for domain, path, authority in (318 (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()319 ):320 if in_domain == domain:321 if path in in_path:322 return authority323324325 def reduce_uri(self, uri, default_port=True):326 """Accept authority or URI and extract only the authority and path."""327 # note HTTP URLs do not have a userinfo component328 parts = urllib2.urlparse.urlsplit(uri)329 if parts[1]:330 # URI331 scheme = parts[0]332 authority = parts[1]333 path = parts[2] or '/'334 else:335 # host or host:port336 scheme = None337 authority = uri338 path = '/'339 host, port = urllib2.splitport(authority)340 if default_port and port is None and scheme is not None:341 dport = {"http": 80,342 "https": 443,343 }.get(scheme)344 if dport is not None:345 authority = "%s:%d" % (host, dport)346347 return authority, path348349350 def is_suburi(self, base, test):351 """Check if test is below base in a URI tree352353 Both args must be URIs in reduced form.354 """355 if base == test:356 return True357 if base[0] != test[0]:358 return False359 common = urllib2.posixpath.commonprefix((base[1], test[1]))360 if len(common) == len(base[1]):361 return True362 return False363364365 def empty(self):366 self.passwd = {}367368369 def remove(self, uri, realm=None):370 # uri could be a single URI or a sequence371 if isinstance(uri, basestring):372 uri = [uri]373374 for default_port in True, False:375 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])376 del self.passwd[reduced_uri][realm]377378379 def __contains__(self, uri):380 # uri could be a single URI or a sequence381 if isinstance(uri, basestring):382 uri = [uri]383384 uri = tuple([self.reduce_uri(u, False) for u in uri])385386 if uri in self.passwd:387 return True388389 return False390391auth_manager = AuthManager()392393394395class AuthObject(object):396 """The :class:`AuthObject` is a simple HTTP Authentication token. When397 given to a Requests function, it enables Basic HTTP Authentication for that398 Request. You can also enable Authorization for domain realms with AutoAuth.399 See AutoAuth for more details.400401 :param username: Username to authenticate with.402 :param password: Password for given username.403 :param realm: (optional) the realm this auth applies to404 :param handler: (optional) basic || digest || proxy_basic || proxy_digest405 """406407 _handlers = {408 'basic': _HTTPBasicAuthHandler,409 'digest': _HTTPDigestAuthHandler,410 'proxy_basic': urllib2.ProxyBasicAuthHandler,411 'proxy_digest': urllib2.ProxyDigestAuthHandler412 }413414 def __init__(self, username, password, handler='basic', realm=None):415 self.username = username416 self.password = password417 self.realm = realm418419 if isinstance(handler, basestring):420 self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)421 else:422 self.handler = handler423424class RequestException(Exception):425 """There was an ambiguous exception that occured while handling your426 request."""427428class AuthenticationError(RequestException):429 """The authentication credentials provided were invalid."""430431class URLRequired(RequestException):432 """A valid URL is required to make a request."""433434class InvalidMethod(RequestException):435 """An inappropriate method was attempted."""
added:requests/monkeys.py+85 added
1# -*- coding: utf-8 -*-23"""4requests.monkeys5~~~~~~~~~~~~~~~~67Monkey patches to urllib2 and the like.89"""1011# import requests12# import urllib13import urllib214# import socket15# import zlib161718class _Request(urllib2.Request):19 """Hidden wrapper around the urllib2.Request object. Allows for manual20 setting of HTTP methods.21 """2223 def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):24 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)25 self.method = method2627 def get_method(self):28 if self.method:29 return self.method3031 return urllib2.Request.get_method(self)323334class _HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):35 # from mercurial3637 def __init__(self, *args, **kwargs):38 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)39 self.retried_req = None4041 def reset_retry_count(self):42 # Python 2.6.5 will call this on 401 or 407 errors and thus loop43 # forever. We disable reset_retry_count completely and reset in44 # http_error_auth_reqed instead.45 pass4647 def http_error_auth_reqed(self, auth_header, host, req, headers):48 # Reset the retry counter once for each request.49 if req is not self.retried_req:50 self.retried_req = req51 self.retried = 052 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(53 self, auth_header, host, req, headers)54555657class _HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):5859 def __init__(self, *args, **kwargs):60 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)61 self.retried_req = None6263 def reset_retry_count(self):64 # Python 2.6.5 will call this on 401 or 407 errors and thus loop65 # forever. We disable reset_retry_count completely and reset in66 # http_error_auth_reqed instead.67 pass6869 def http_error_auth_reqed(self, auth_header, host, req, headers):70 # Reset the retry counter once for each request.71 if req is not self.retried_req:72 self.retried_req = req73 self.retried = 074 # In python < 2.5 AbstractDigestAuthHandler raises a ValueError if75 # it doesn't know about the auth type requested. This can happen if76 # somebody is using BasicAuth and types a bad password.7778 try:79 return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(80 self, auth_header, host, req, headers)81 except ValueError, inst:82 arg = inst.args[0]83 if arg.startswith("AbstractDigestAuthHandler doesn't know "):84 return85 raise
added:requests/patches.py+5 added
1# -*- coding: utf-8 -*-23"""4requests.monkeys5"""
modified:test_requests.py+1 added-1 removed
121 unmodified lines
122 def test_cookie_jar(self):123 """124 .. todo:: This really doesn't test to make sure the cookie is working125 """126127 jar = cookielib.CookieJar()128 self.assertFalse(jar)129130 requests.get('http://google.com', cookies=jar)
23 unmodified lines
154 conv_auth = ('requeststest', 'bad_password')155156 r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)157 self.assertEquals(r.status_code, 401)157 print r.__dict__158159160if __name__ == '__main__':161 unittest.main()