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
Provenance
- Commit
0c00a17- Tree
2af7a3e- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
7215452- Parent 2
fa1db95
8 files changed+668 added−544 removed
added:requests/api.py+115 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.api5+~~~~~~~~~~~~6+7+This module impliments the Requests API.8+9+:copyright: (c) 2011 by Kenneth Reitz.10+:license: ISC, see LICENSE for more details.11+12+"""13+14+import requests15+from .models import Request, Response, AuthManager, AuthObject, auth_manager16+17+18+__all__ = ('request', 'get', 'head', 'post', 'put', 'delete')19+20+21+22+def request(method, url, **kwargs):23+ """Sends a `method` request. Returns :class:`Response` object.24+25+ :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())36+37+ 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()42+43+ return r.response44+45+46+def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):47+ """Sends a GET request. Returns :class:`Response` object.48+49+ :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+ """56+57+ return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)58+59+60+def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):61+ """Sends a HEAD request. Returns :class:`Response` object.62+63+ :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+ """70+71+ return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)72+73+74+def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):75+ """Sends a POST request. Returns :class:`Response` object.76+77+ :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+ """85+86+ return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)87+88+89+def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):90+ """Sends a PUT request. Returns :class:`Response` object.91+92+ :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+ """100+101+ return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)102+103+104+def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):105+ """Sends a DELETE request. Returns :class:`Response` object.106+107+ :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+ """114+115+ 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 -*-2 3 """4- requests.core5- ~~~~~~~~~~~~~4+requests.core5+~~~~~~~~~~~~~6 7- This module implements the main Requests system.7+This module implements the main Requests system.8 9- :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.11+12 """13 13-from __future__ import absolute_import14-15-import requests16-import urllib17-import urllib218-import socket19-import zlib20-21-from urllib2 import HTTPError22-from urlparse import urlparse23-24-from .packages.poster.encode import multipart_encode25-from .packages.poster.streaminghttp import register_openers, get_handlers26-27-14 __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'20 35-__all__ = [36- 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete',37- 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError',38- 'URLRequired', 'InvalidMethod', 'HTTPError'39-]21 41-42-class _Request(urllib2.Request):43- """Hidden wrapper around the urllib2.Request object. Allows for manual44- setting of HTTP methods.45- """46-47- 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 = method50-51- def get_method(self):52- if self.method:53- return self.method54-55- return urllib2.Request.get_method(self)56-57-58-class Request(object):59- """The :class:`Request` object. It carries out all functionality of60- Requests. Recommended interface is with the Requests functions.61- """62-63- _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')64-65- def __init__(self, url=None, headers=dict(), files=None, method=None,66- data=dict(), auth=None, cookiejar=None, timeout=None):67-68- self.url = url69- self.headers = headers70- self.files = files71- self.method = method72- self.data = data73-74- socket.setdefaulttimeout(timeout)75-76- for (k, v) in self.data.iteritems():77- self.data[k] = v.encode('utf-8')78-79- # 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.data84-85- self.response = Response()86-87- 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 = False94-95-96- def __repr__(self):97- return '<Request [%s]>' % (self.method)98-99-100- def __setattr__(self, name, value):101- if (name == 'method') and (value):102- if not value in self._METHODS:103- raise InvalidMethod()104-105- object.__setattr__(self, name, value)106-107-108- def _checks(self):109- """Deterministic checks for consistency."""110-111- if not self.url:112- raise URLRequired113-114-115- def _get_opener(self):116- """Creates appropriate opener object for urllib2."""117-118- _handlers = []119-120- if self.cookiejar is not None:121- _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))122-123- 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)128-129- _handlers.append(self.auth.handler)130-131- if not _handlers:132- return urllib2.urlopen133-134- _handlers.extend(get_handlers())135- opener = urllib2.build_opener(*_handlers)136-137- 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))145-146- return opener.open147-148- def _build_response(self, resp):149- """Build internal Response object from given response."""150-151- self.response.status_code = getattr(resp, 'code', None)152- self.response.headers = getattr(resp.info(), 'dict', None)153- self.response.content = resp.read()154-155- 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- pass160-161- self.response.url = getattr(resp, 'url', None)162-163-164- @staticmethod165- def _build_url(url, data=None):166- """Build URLs."""167-168- 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 url175-176-177- 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.181-182- Once a request is successfully sent, `sent` will equal True.183-184- :param anyway: If True, request will be sent, even if it has185- already been sent.186- """187- self._checks()188- success = False189-190- if self.method in ('GET', 'HEAD', 'DELETE'):191- req = _Request(self._build_url(self.url, self._enc_data), method=self.method)192- else:193-194- if self.files:195- register_openers()196-197- if self.data:198- self.files.update(self.data)199-200- datagen, headers = multipart_encode(self.files)201- req = _Request(self.url, data=datagen, headers=headers, method=self.method)202-203- else:204- req = _Request(self.url, data=self._enc_data, method=self.method)205-206- if self.headers:207- req.headers.update(self.headers)208-209- if not self.sent or anyway:210-211-212-213- try:214- opener = self._get_opener()215- resp = opener(req)216-217- if self.cookiejar is not None:218- self.cookiejar.extract_cookies(resp, req)219-220- except urllib2.HTTPError, why:221- self._build_response(why)222- self.response.error = why223- else:224- self._build_response(resp)225- self.response.ok = True226-227- self.response.cached = False228- else:229- self.response.cached = True230-231- self.sent = self.response.ok232-233- return self.sent234-235-236- def read(self, *args):237- return self.response.read()238-239-240-241-class 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- """246-247- 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 = False255-256-257- def __repr__(self):258- return '<Response [%s]>' % (self.status_code)259-260-261- def __nonzero__(self):262- """Returns true if status_code is 'OK'."""263- return not self.error264-265-266- def raise_for_status(self):267- """Raises stored HTTPError if one exists."""268- if self.error:269- raise self.error270-271- def read(self, *args):272- return self.content273-274-275-276-class AuthManager(object):277- """Authentication Manager."""278-279- def __new__(cls):280- singleton = cls.__dict__.get('__singleton__')281- if singleton is not None:282- return singleton283-284- cls.__singleton__ = singleton = object.__new__(cls)285-286- return singleton287-288-289- def __init__(self):290- self.passwd = {}291- self._auth = {}292-293-294- def __repr__(self):295- return '<AuthManager [%s]>' % (self.method)296-297-298- def add_auth(self, uri, auth):299- """Registers AuthObject to AuthManager."""300-301- uri = self.reduce_uri(uri, False)302-303- # try to make it an AuthObject304- if not isinstance(auth, AuthObject):305- try:306- auth = AuthObject(*auth)307- except TypeError:308- pass309-310- self._auth[uri] = auth311-312-313- 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]318-319- reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])320-321- if reduced_uri not in self.passwd:322- self.passwd[reduced_uri] = {}323- self.passwd[reduced_uri] = (user, passwd)324-325-326- 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 authinfo332-333- return (None, None)334-335-336- def get_auth(self, uri):337- (in_domain, in_path) = self.reduce_uri(uri, False)338-339- 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 authority345-346-347- 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)368-369- return authority, path370-371-372- def is_suburi(self, base, test):373- """Check if test is below base in a URI tree374-375- 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 False385-386-387- def empty(self):388- self.passwd = {}389-390-391- def remove(self, uri, realm=None):392- # uri could be a single URI or a sequence393- if isinstance(uri, basestring):394- uri = [uri]395-396- 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]399-400-401- def __contains__(self, uri):402- # uri could be a single URI or a sequence403- if isinstance(uri, basestring):404- uri = [uri]405-406- uri = tuple([self.reduce_uri(u, False) for u in uri])407-408- if uri in self.passwd:409- return True410-411- return False412-413-auth_manager = AuthManager()414-415-416-417-class 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.422-423- :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- """428-429- _handlers = {430- 'basic': urllib2.HTTPBasicAuthHandler,431- 'digest': urllib2.HTTPDigestAuthHandler,432- 'proxy_basic': urllib2.ProxyBasicAuthHandler,433- 'proxy_digest': urllib2.ProxyDigestAuthHandler434- }435-436- def __init__(self, username, password, handler='basic', realm=None):437- self.username = username438- self.password = password439- self.realm = realm440-441- if isinstance(handler, basestring):442- self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)443- else:444- self.handler = handler445-446-447-448-449-def request(method, url, **kwargs):450- """Sends a `method` request. Returns :class:`Response` object.451-452- :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())463-464- 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()469-470- return r.response471-472-473-def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):474- """Sends a GET request. Returns :class:`Response` object.475-476- :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- """483-484- return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)485-486-487-def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):488- """Sends a HEAD request. Returns :class:`Response` object.489-490- :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- """497-498- return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)499-500-501-def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):502- """Sends a POST request. Returns :class:`Response` object.503-504- :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- """512-513- return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)514-515-516-def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):517- """Sends a PUT request. Returns :class:`Response` object.518-519- :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- """527-528- return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)529-530-531-def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):532- """Sends a DELETE request. Returns :class:`Response` object.533-534- :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- """541-542- return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)543-544-545-546-class RequestException(Exception):547- """There was an ambiguous exception that occured while handling your548- request."""549-550-class AuthenticationError(RequestException):551- """The authentication credentials provided were invalid."""552-553-class URLRequired(RequestException):554- """A valid URL is required to make a request."""555-556-class InvalidMethod(RequestException):557- """An inappropriate method was attempted."""22+from .models import HTTPError, auth_manager23+from .api import *added:requests/models.py+435 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.system5+~~~~~~~~~~~~~~~6+7+"""8+9+import requests10+import urllib11+import urllib212+import socket13+import zlib14+15+from urllib2 import HTTPError16+from urlparse import urlparse17+18+from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler19+20+from .packages.poster.encode import multipart_encode21+from .packages.poster.streaminghttp import register_openers, get_handlers22+23+24+25+class Request(object):26+ """The :class:`Request` object. It carries out all functionality of27+ Requests. Recommended interface is with the Requests functions.28+ """29+30+ _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')31+32+ def __init__(self, url=None, headers=dict(), files=None, method=None,33+ data=dict(), auth=None, cookiejar=None, timeout=None):34+35+ socket.setdefaulttimeout(timeout)36+37+ self.url = url38+ self.headers = headers39+ self.files = files40+ self.method = method41+ self.data = {}42+43+ # 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+ })50+51+ # 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 = data56+57+58+ self.response = Response()59+60+ 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 = False67+68+69+ def __repr__(self):70+ return '<Request [%s]>' % (self.method)71+72+73+ def __setattr__(self, name, value):74+ if (name == 'method') and (value):75+ if not value in self._METHODS:76+ raise InvalidMethod()77+78+ object.__setattr__(self, name, value)79+80+81+ def _checks(self):82+ """Deterministic checks for consistency."""83+84+ if not self.url:85+ raise URLRequired86+87+88+ def _get_opener(self):89+ """Creates appropriate opener object for urllib2."""90+91+ _handlers = []92+93+ if self.cookiejar is not None:94+ _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))95+96+ 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)101+102+ _handlers.append(self.auth.handler)103+104+ if not _handlers:105+ return urllib2.urlopen106+107+ _handlers.extend(get_handlers())108+ opener = urllib2.build_opener(*_handlers)109+110+ 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))118+119+ return opener.open120+121+ def _build_response(self, resp):122+ """Build internal Response object from given response."""123+ if isinstance(resp, HTTPError):124+ # print resp.__dict__125+ pass126+127+ self.response.status_code = getattr(resp, 'code', None)128+129+ try:130+ self.response.headers = getattr(resp.info(), 'dict', None)131+ self.response.content = resp.read()132+ except AttributeError, why:133+ pass134+135+ 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+ pass140+141+ self.response.url = getattr(resp, 'url', None)142+143+144+ @staticmethod145+ def _build_url(url, data=None):146+ """Build URLs."""147+148+ 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 url155+156+157+ 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.161+162+ Once a request is successfully sent, `sent` will equal True.163+164+ :param anyway: If True, request will be sent, even if it has165+ already been sent.166+ """167+ self._checks()168+ success = False169+170+ if self.method in ('GET', 'HEAD', 'DELETE'):171+ req = _Request(self._build_url(self.url, self._enc_data), method=self.method)172+ else:173+174+ if self.files:175+ register_openers()176+177+ if self.data:178+ self.files.update(self.data)179+180+ datagen, headers = multipart_encode(self.files)181+ req = _Request(self.url, data=datagen, headers=headers, method=self.method)182+183+ else:184+ req = _Request(self.url, data=self._enc_data, method=self.method)185+186+ if self.headers:187+ req.headers.update(self.headers)188+189+ if not self.sent or anyway:190+191+ try:192+ opener = self._get_opener()193+ resp = opener(req)194+195+ if self.cookiejar is not None:196+ self.cookiejar.extract_cookies(resp, req)197+198+ except urllib2.HTTPError, why:199+ self._build_response(why)200+ self.response.error = why201+ else:202+ self._build_response(resp)203+ self.response.ok = True204+205+ self.response.cached = False206+ else:207+ self.response.cached = True208+209+ self.sent = self.response.ok210+211+ return self.sent212+213+214+ def read(self, *args):215+ return self.response.read()216+217+218+219+class 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+ """224+225+ 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 = False233+234+235+ def __repr__(self):236+ return '<Response [%s]>' % (self.status_code)237+238+239+ def __nonzero__(self):240+ """Returns true if status_code is 'OK'."""241+ return not self.error242+243+244+ def raise_for_status(self):245+ """Raises stored HTTPError if one exists."""246+ if self.error:247+ raise self.error248+249+ def read(self, *args):250+ return self.content251+252+253+254+class AuthManager(object):255+ """Authentication Manager."""256+257+ def __new__(cls):258+ singleton = cls.__dict__.get('__singleton__')259+ if singleton is not None:260+ return singleton261+262+ cls.__singleton__ = singleton = object.__new__(cls)263+264+ return singleton265+266+267+ def __init__(self):268+ self.passwd = {}269+ self._auth = {}270+271+272+ def __repr__(self):273+ return '<AuthManager [%s]>' % (self.method)274+275+276+ def add_auth(self, uri, auth):277+ """Registers AuthObject to AuthManager."""278+279+ uri = self.reduce_uri(uri, False)280+281+ # try to make it an AuthObject282+ if not isinstance(auth, AuthObject):283+ try:284+ auth = AuthObject(*auth)285+ except TypeError:286+ pass287+288+ self._auth[uri] = auth289+290+291+ 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]296+297+ reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])298+299+ if reduced_uri not in self.passwd:300+ self.passwd[reduced_uri] = {}301+ self.passwd[reduced_uri] = (user, passwd)302+303+304+ 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 authinfo310+311+ return (None, None)312+313+314+ def get_auth(self, uri):315+ (in_domain, in_path) = self.reduce_uri(uri, False)316+317+ 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 authority323+324+325+ 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)346+347+ return authority, path348+349+350+ def is_suburi(self, base, test):351+ """Check if test is below base in a URI tree352+353+ 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 False363+364+365+ def empty(self):366+ self.passwd = {}367+368+369+ def remove(self, uri, realm=None):370+ # uri could be a single URI or a sequence371+ if isinstance(uri, basestring):372+ uri = [uri]373+374+ 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]377+378+379+ def __contains__(self, uri):380+ # uri could be a single URI or a sequence381+ if isinstance(uri, basestring):382+ uri = [uri]383+384+ uri = tuple([self.reduce_uri(u, False) for u in uri])385+386+ if uri in self.passwd:387+ return True388+389+ return False390+391+auth_manager = AuthManager()392+393+394+395+class 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.400+401+ :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+ """406+407+ _handlers = {408+ 'basic': HTTPBasicAuthHandler,409+ 'digest': HTTPDigestAuthHandler,410+ 'proxy_basic': urllib2.ProxyBasicAuthHandler,411+ 'proxy_digest': urllib2.ProxyDigestAuthHandler412+ }413+414+ def __init__(self, username, password, handler='basic', realm=None):415+ self.username = username416+ self.password = password417+ self.realm = realm418+419+ if isinstance(handler, basestring):420+ self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)421+ else:422+ self.handler = handler423+424+class RequestException(Exception):425+ """There was an ambiguous exception that occured while handling your426+ request."""427+428+class AuthenticationError(RequestException):429+ """The authentication credentials provided were invalid."""430+431+class URLRequired(RequestException):432+ """A valid URL is required to make a request."""433+434+class InvalidMethod(RequestException):435+ """An inappropriate method was attempted."""added:requests/monkeys.py+81 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.monkeys5+~~~~~~~~~~~~~~~~6+7+Urllib2 Monkey patches.8+9+"""10+11+import urllib212+13+14+class Request(urllib2.Request):15+ """Hidden wrapper around the urllib2.Request object. Allows for manual16+ setting of HTTP methods.17+ """18+19+ 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 = method22+23+ def get_method(self):24+ if self.method:25+ return self.method26+27+ return urllib2.Request.get_method(self)28+29+30+class HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):31+ # from mercurial32+33+ def __init__(self, *args, **kwargs):34+ urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)35+ self.retried_req = None36+37+ 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+ pass42+43+ 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)50+51+52+53+class HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):54+55+ def __init__(self, *args, **kwargs):56+ urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)57+ self.retried_req = None58+59+ 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+ pass64+65+ 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.73+74+ 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+ raiseadded:requests/patches.py+5 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.monkeys5+"""modified:AUTHORS+1 added
16 unmodified lines17 - Justin Murphy18 - Rob Madole19 - Aram Dulyan20 - Johannes Gorset21+- 村山めがね (Megan Emurayama)modified:HISTORY.rst+9 added
1 History2 -------3 4+0.3.45++++++6+7+* Urllib2 HTTPAuthentication Recursion fix (Basic/Digest)8+* Internal Refactor9+* Bytes data upload Bugfix10+11+12+13 0.3.3 (2011-05-12)14 ++++++++++++++++++15 16 * Request timeouts76 unmodified linesmodified:test_requests.py+12 added
77 unmodified lines78 79 post2 = requests.post(bin.url, files={'some': open('test_requests.py')})80 self.assertEqual(post2.status_code, 201)81 82+ post3 = requests.post(bin.url, data='[{"some": "json"}]')83+ self.assertEqual(post.status_code, 201)84+85 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):86 bin = requests.post('http://www.postbin.org/')87 88 self.assertEqual(bin.status_code, 200)33 unmodified lines122 def test_cookie_jar(self):123 """124 .. todo:: This really doesn't test to make sure the cookie is working125 """126+127 jar = cookielib.CookieJar()128 self.assertFalse(jar)129 130 requests.get('http://google.com', cookies=jar)13 unmodified lines144 self.assertEquals(r.status_code, 200)145 146 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'})152 153+ def test_httpauth_recursion(self):154+ conv_auth = ('requeststest', 'bad_password')155 156+ r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)157+ self.assertEquals(r.status_code, 401)158+159+160 if __name__ == '__main__':161 unittest.main()