Skip to content
Myr

Merge branch 'release/0.3.4'

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 · parents 7215452, fa1db95 · Browse files · 8 files+668 added−544 removed
This commit

State

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

Diff stats

8 files+668 added−544 removed

  • other:+668 added−544 removed

8 files+668 added−544 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+10 added-544 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'29__version__ = '0.3.3'30__build__ = 0x00030315__version__ = '0.3.4'16__build__ = 0x00030417__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 Request(object):59 """The :class:`Request` object. It carries out all functionality of60 Requests. Recommended interface is with the Requests functions.61 """6263 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')6465 def __init__(self, url=None, headers=dict(), files=None, method=None,66 data=dict(), auth=None, cookiejar=None, timeout=None):6768 self.url = url69 self.headers = headers70 self.files = files71 self.method = method72 self.data = data7374 socket.setdefaulttimeout(timeout)7576 for (k, v) in self.data.iteritems():77 self.data[k] = v.encode('utf-8')7879 # url encode data if it's a dict80 if hasattr(data, 'items'):81 self._enc_data = urllib.urlencode(self.data)82 else:83 self._enc_data = self.data8485 self.response = Response()8687 if isinstance(auth, (list, tuple)):88 auth = AuthObject(*auth)89 if not auth:90 auth = auth_manager.get_auth(self.url)91 self.auth = auth92 self.cookiejar = cookiejar93 self.sent = False949596 def __repr__(self):97 return '<Request [%s]>' % (self.method)9899100 def __setattr__(self, name, value):101 if (name == 'method') and (value):102 if not value in self._METHODS:103 raise InvalidMethod()104105 object.__setattr__(self, name, value)106107108 def _checks(self):109 """Deterministic checks for consistency."""110111 if not self.url:112 raise URLRequired113114115 def _get_opener(self):116 """Creates appropriate opener object for urllib2."""117118 _handlers = []119120 if self.cookiejar is not None:121 _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))122123 if self.auth:124 if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):125 auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)126 self.auth.handler = self.auth.handler(auth_manager)127 auth_manager.add_auth(self.url, self.auth)128129 _handlers.append(self.auth.handler)130131 if not _handlers:132 return urllib2.urlopen133134 _handlers.extend(get_handlers())135 opener = urllib2.build_opener(*_handlers)136137 if self.headers:138 # Allow default headers in the opener to be overloaded139 normal_keys = [k.capitalize() for k in self.headers]140 for key, val in opener.addheaders[:]:141 if key not in normal_keys:142 continue143 # Remove it, we have a value to take its place144 opener.addheaders.remove((key, val))145146 return opener.open147148 def _build_response(self, resp):149 """Build internal Response object from given response."""150151 self.response.status_code = getattr(resp, 'code', None)152 self.response.headers = getattr(resp.info(), 'dict', None)153 self.response.content = resp.read()154155 if self.response.headers.get('content-encoding', None) == 'gzip':156 try:157 self.response.content = zlib.decompress(self.response.content, 16+zlib.MAX_WBITS)158 except zlib.error:159 pass160161 self.response.url = getattr(resp, 'url', None)162163164 @staticmethod165 def _build_url(url, data=None):166 """Build URLs."""167168 if urlparse(url).query:169 return '%s&%s' % (url, data)170 else:171 if data:172 return '%s?%s' % (url, data)173 else:174 return url175176177 def send(self, anyway=False):178 """Sends the request. Returns True of successful, false if not.179 If there was an HTTPError during transmission,180 self.response.status_code will contain the HTTPError code.181182 Once a request is successfully sent, `sent` will equal True.183184 :param anyway: If True, request will be sent, even if it has185 already been sent.186 """187 self._checks()188 success = False189190 if self.method in ('GET', 'HEAD', 'DELETE'):191 req = _Request(self._build_url(self.url, self._enc_data), method=self.method)192 else:193194 if self.files:195 register_openers()196197 if self.data:198 self.files.update(self.data)199200 datagen, headers = multipart_encode(self.files)201 req = _Request(self.url, data=datagen, headers=headers, method=self.method)202203 else:204 req = _Request(self.url, data=self._enc_data, method=self.method)205206 if self.headers:207 req.headers.update(self.headers)208209 if not self.sent or anyway:210211212213 try:214 opener = self._get_opener()215 resp = opener(req)216217 if self.cookiejar is not None:218 self.cookiejar.extract_cookies(resp, req)219220 except urllib2.HTTPError, why:221 self._build_response(why)222 self.response.error = why223 else:224 self._build_response(resp)225 self.response.ok = True226227 self.response.cached = False228 else:229 self.response.cached = True230231 self.sent = self.response.ok232233 return self.sent234235236 def read(self, *args):237 return self.response.read()238239240241class Response(object):242 """The :class:`Request` object. All :class:`Request` objects contain a243 :class:`Request.response <response>` attribute, which is an instance of244 this class.245 """246247 def __init__(self):248 self.content = None249 self.status_code = None250 self.headers = dict()251 self.url = None252 self.ok = False253 self.error = None254 self.cached = False255256257 def __repr__(self):258 return '<Response [%s]>' % (self.status_code)259260261 def __nonzero__(self):262 """Returns true if status_code is 'OK'."""263 return not self.error264265266 def raise_for_status(self):267 """Raises stored HTTPError if one exists."""268 if self.error:269 raise self.error270271 def read(self, *args):272 return self.content273274275276class AuthManager(object):277 """Authentication Manager."""278279 def __new__(cls):280 singleton = cls.__dict__.get('__singleton__')281 if singleton is not None:282 return singleton283284 cls.__singleton__ = singleton = object.__new__(cls)285286 return singleton287288289 def __init__(self):290 self.passwd = {}291 self._auth = {}292293294 def __repr__(self):295 return '<AuthManager [%s]>' % (self.method)296297298 def add_auth(self, uri, auth):299 """Registers AuthObject to AuthManager."""300301 uri = self.reduce_uri(uri, False)302303 # try to make it an AuthObject304 if not isinstance(auth, AuthObject):305 try:306 auth = AuthObject(*auth)307 except TypeError:308 pass309310 self._auth[uri] = auth311312313 def add_password(self, realm, uri, user, passwd):314 """Adds password to AuthManager."""315 # uri could be a single URI or a sequence316 if isinstance(uri, basestring):317 uri = [uri]318319 reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])320321 if reduced_uri not in self.passwd:322 self.passwd[reduced_uri] = {}323 self.passwd[reduced_uri] = (user, passwd)324325326 def find_user_password(self, realm, authuri):327 for uris, authinfo in self.passwd.iteritems():328 reduced_authuri = self.reduce_uri(authuri, False)329 for uri in uris:330 if self.is_suburi(uri, reduced_authuri):331 return authinfo332333 return (None, None)334335336 def get_auth(self, uri):337 (in_domain, in_path) = self.reduce_uri(uri, False)338339 for domain, path, authority in (340 (i[0][0], i[0][1], i[1]) for i in self._auth.iteritems()341 ):342 if in_domain == domain:343 if path in in_path:344 return authority345346347 def reduce_uri(self, uri, default_port=True):348 """Accept authority or URI and extract only the authority and path."""349 # note HTTP URLs do not have a userinfo component350 parts = urllib2.urlparse.urlsplit(uri)351 if parts[1]:352 # URI353 scheme = parts[0]354 authority = parts[1]355 path = parts[2] or '/'356 else:357 # host or host:port358 scheme = None359 authority = uri360 path = '/'361 host, port = urllib2.splitport(authority)362 if default_port and port is None and scheme is not None:363 dport = {"http": 80,364 "https": 443,365 }.get(scheme)366 if dport is not None:367 authority = "%s:%d" % (host, dport)368369 return authority, path370371372 def is_suburi(self, base, test):373 """Check if test is below base in a URI tree374375 Both args must be URIs in reduced form.376 """377 if base == test:378 return True379 if base[0] != test[0]:380 return False381 common = urllib2.posixpath.commonprefix((base[1], test[1]))382 if len(common) == len(base[1]):383 return True384 return False385386387 def empty(self):388 self.passwd = {}389390391 def remove(self, uri, realm=None):392 # uri could be a single URI or a sequence393 if isinstance(uri, basestring):394 uri = [uri]395396 for default_port in True, False:397 reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])398 del self.passwd[reduced_uri][realm]399400401 def __contains__(self, uri):402 # uri could be a single URI or a sequence403 if isinstance(uri, basestring):404 uri = [uri]405406 uri = tuple([self.reduce_uri(u, False) for u in uri])407408 if uri in self.passwd:409 return True410411 return False412413auth_manager = AuthManager()414415416417class AuthObject(object):418 """The :class:`AuthObject` is a simple HTTP Authentication token. When419 given to a Requests function, it enables Basic HTTP Authentication for that420 Request. You can also enable Authorization for domain realms with AutoAuth.421 See AutoAuth for more details.422423 :param username: Username to authenticate with.424 :param password: Password for given username.425 :param realm: (optional) the realm this auth applies to426 :param handler: (optional) basic || digest || proxy_basic || proxy_digest427 """428429 _handlers = {430 'basic': urllib2.HTTPBasicAuthHandler,431 'digest': urllib2.HTTPDigestAuthHandler,432 'proxy_basic': urllib2.ProxyBasicAuthHandler,433 'proxy_digest': urllib2.ProxyDigestAuthHandler434 }435436 def __init__(self, username, password, handler='basic', realm=None):437 self.username = username438 self.password = password439 self.realm = realm440441 if isinstance(handler, basestring):442 self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)443 else:444 self.handler = handler445446447448449def request(method, url, **kwargs):450 """Sends a `method` request. Returns :class:`Response` object.451452 :param method: method for the new :class:`Request` object.453 :param url: URL for the new :class:`Request` object.454 :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.455 :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.456 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.457 :param cookies: (optional) CookieJar object to send with the :class:`Request`.458 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.459 :param auth: (optional) AuthObject to enable Basic HTTP Auth.460 :param timeout: (optional) Float describing the timeout of the request.461 """462 data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())463464 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),465 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),466 auth=kwargs.pop('auth', auth_manager.get_auth(url)),467 timeout=kwargs.pop('timeout', requests.timeout))468 r.send()469470 return r.response471472473def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):474 """Sends a GET request. Returns :class:`Response` object.475476 :param url: URL for the new :class:`Request` object.477 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.478 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.479 :param cookies: (optional) CookieJar object to send with the :class:`Request`.480 :param auth: (optional) AuthObject to enable Basic HTTP Auth.481 :param timeout: (optional) Float describing the timeout of the request.482 """483484 return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)485486487def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):488 """Sends a HEAD request. Returns :class:`Response` object.489490 :param url: URL for the new :class:`Request` object.491 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.492 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.493 :param cookies: (optional) CookieJar object to send with the :class:`Request`.494 :param auth: (optional) AuthObject to enable Basic HTTP Auth.495 :param timeout: (optional) Float describing the timeout of the request.496 """497498 return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)499500501def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):502 """Sends a POST request. Returns :class:`Response` object.503504 :param url: URL for the new :class:`Request` object.505 :param data: (optional) Dictionary of POST data to send with the :class:`Request`.506 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.507 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.508 :param cookies: (optional) CookieJar object to send with the :class:`Request`.509 :param auth: (optional) AuthObject to enable Basic HTTP Auth.510 :param timeout: (optional) Float describing the timeout of the request.511 """512513 return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)514515516def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):517 """Sends a PUT request. Returns :class:`Response` object.518519 :param url: URL for the new :class:`Request` object.520 :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.521 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.522 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.523 :param cookies: (optional) CookieJar object to send with the :class:`Request`.524 :param auth: (optional) AuthObject to enable Basic HTTP Auth.525 :param timeout: (optional) Float describing the timeout of the request.526 """527528 return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)529530531def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):532 """Sends a DELETE request. Returns :class:`Response` object.533534 :param url: URL for the new :class:`Request` object.535 :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.536 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.537 :param cookies: (optional) CookieJar object to send with the :class:`Request`.538 :param auth: (optional) AuthObject to enable Basic HTTP Auth.539 :param timeout: (optional) Float describing the timeout of the request.540 """541542 return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)543544545546class RequestException(Exception):547 """There was an ambiguous exception that occured while handling your548 request."""549550class AuthenticationError(RequestException):551 """The authentication credentials provided were invalid."""552553class URLRequired(RequestException):554 """A valid URL is required to make a request."""555556class InvalidMethod(RequestException):557 """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 as _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+81 added
1# -*- coding: utf-8 -*-23"""4requests.monkeys5~~~~~~~~~~~~~~~~67Urllib2 Monkey patches.89"""1011import urllib2121314class Request(urllib2.Request):15 """Hidden wrapper around the urllib2.Request object. Allows for manual16 setting of HTTP methods.17 """1819 def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):20 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)21 self.method = method2223 def get_method(self):24 if self.method:25 return self.method2627 return urllib2.Request.get_method(self)282930class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):31 # from mercurial3233 def __init__(self, *args, **kwargs):34 urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)35 self.retried_req = None3637 def reset_retry_count(self):38 # Python 2.6.5 will call this on 401 or 407 errors and thus loop39 # forever. We disable reset_retry_count completely and reset in40 # http_error_auth_reqed instead.41 pass4243 def http_error_auth_reqed(self, auth_header, host, req, headers):44 # Reset the retry counter once for each request.45 if req is not self.retried_req:46 self.retried_req = req47 self.retried = 048 return urllib2.HTTPBasicAuthHandler.http_error_auth_reqed(49 self, auth_header, host, req, headers)50515253class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):5455 def __init__(self, *args, **kwargs):56 urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)57 self.retried_req = None5859 def reset_retry_count(self):60 # Python 2.6.5 will call this on 401 or 407 errors and thus loop61 # forever. We disable reset_retry_count completely and reset in62 # http_error_auth_reqed instead.63 pass6465 def http_error_auth_reqed(self, auth_header, host, req, headers):66 # Reset the retry counter once for each request.67 if req is not self.retried_req:68 self.retried_req = req69 self.retried = 070 # In python < 2.5 AbstractDigestAuthHandler raises a ValueError if71 # it doesn't know about the auth type requested. This can happen if72 # somebody is using BasicAuth and types a bad password.7374 try:75 return urllib2.HTTPDigestAuthHandler.http_error_auth_reqed(76 self, auth_header, host, req, headers)77 except ValueError, inst:78 arg = inst.args[0]79 if arg.startswith("AbstractDigestAuthHandler doesn't know "):80 return81 raise
added:requests/patches.py+5 added
1# -*- coding: utf-8 -*-23"""4requests.monkeys5"""
modified:AUTHORS+1 added
16 unmodified lines
17- Justin Murphy18- Rob Madole19- Aram Dulyan20- Johannes Gorset21- 村山めがね (Megan Emurayama)
modified:HISTORY.rst+9 added
1History2-------340.3.45+++++67* Urllib2 HTTPAuthentication Recursion fix (Basic/Digest)8* Internal Refactor9* Bytes data upload Bugfix101112130.3.3 (2011-05-12)14++++++++++++++++++1516* Request timeouts
76 unmodified lines
modified:test_requests.py+12 added
77 unmodified lines
7879 post2 = requests.post(bin.url, files={'some': open('test_requests.py')})80 self.assertEqual(post2.status_code, 201)8182 post3 = requests.post(bin.url, data='[{"some": "json"}]')83 self.assertEqual(post.status_code, 201)8485 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):86 bin = requests.post('http://www.postbin.org/')8788 self.assertEqual(bin.status_code, 200)
33 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)
13 unmodified lines
144 self.assertEquals(r.status_code, 200)145146 def test_unicode_get(self):147 requests.get('http://google.com', params={'foo': u'føø'})148 requests.get('http://google.com', params={u'føø': u'føø'})149 requests.get('http://google.com', params={'føø': 'føø'})150 requests.get('http://google.com', params={'foo': u'foo'})151 requests.get('http://google.com/ø', params={'foo': u'foo'})152153 def test_httpauth_recursion(self):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)158159160if __name__ == '__main__':161 unittest.main()