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
Provenance
- Commit
14ef462- Tree
ded7da0- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
1421ffa
6 files changed+649 added−576 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+8 added-575 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'15 __version__ = '0.3.3'16 __build__ = 0x00030317 __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 _HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):59- # from mercurial60-61- def __init__(self, *args, **kwargs):62- urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)63- self.retried_req = None64-65- 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- pass70-71- 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)78-79-80-class Request(object):81- """The :class:`Request` object. It carries out all functionality of82- Requests. Recommended interface is with the Requests functions.83- """84-85- _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')86-87- def __init__(self, url=None, headers=dict(), files=None, method=None,88- data=dict(), auth=None, cookiejar=None, timeout=None):89-90- socket.setdefaulttimeout(timeout)91-92- self.url = url93- self.headers = headers94- self.files = files95- self.method = method96- self.data = {}97-98- # 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- })105-106- # 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 = data111-112-113- self.response = Response()114-115- 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 = False122-123-124- def __repr__(self):125- return '<Request [%s]>' % (self.method)126-127-128- def __setattr__(self, name, value):129- if (name == 'method') and (value):130- if not value in self._METHODS:131- raise InvalidMethod()132-133- object.__setattr__(self, name, value)134-135-136- def _checks(self):137- """Deterministic checks for consistency."""138-139- if not self.url:140- raise URLRequired141-142-143- def _get_opener(self):144- """Creates appropriate opener object for urllib2."""145-146- _handlers = []147-148- if self.cookiejar is not None:149- _handlers.append(urllib2.HTTPCookieProcessor(self.cookiejar))150-151- 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)156-157- _handlers.append(self.auth.handler)158-159- if not _handlers:160- return urllib2.urlopen161-162- _handlers.extend(get_handlers())163- opener = urllib2.build_opener(*_handlers)164-165- 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))173-174- return opener.open175-176- def _build_response(self, resp):177- """Build internal Response object from given response."""178- if isinstance(resp, HTTPError):179- # print resp.__dict__180- pass181-182- self.response.status_code = getattr(resp, 'code', None)183-184- try:185- self.response.headers = getattr(resp.info(), 'dict', None)186- self.response.content = resp.read()187- except AttributeError, why:188- pass189-190- 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- pass195-196- self.response.url = getattr(resp, 'url', None)197-198-199- @staticmethod200- def _build_url(url, data=None):201- """Build URLs."""202-203- 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 url210-211-212- 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.216-217- Once a request is successfully sent, `sent` will equal True.218-219- :param anyway: If True, request will be sent, even if it has220- already been sent.221- """222- self._checks()223- success = False224-225- if self.method in ('GET', 'HEAD', 'DELETE'):226- req = _Request(self._build_url(self.url, self._enc_data), method=self.method)227- else:228-229- if self.files:230- register_openers()231-232- if self.data:233- self.files.update(self.data)234-235- datagen, headers = multipart_encode(self.files)236- req = _Request(self.url, data=datagen, headers=headers, method=self.method)237-238- else:239- req = _Request(self.url, data=self._enc_data, method=self.method)240-241- if self.headers:242- req.headers.update(self.headers)243-244- if not self.sent or anyway:245-246- try:247- opener = self._get_opener()248- resp = opener(req)249-250- if self.cookiejar is not None:251- self.cookiejar.extract_cookies(resp, req)252-253- except urllib2.HTTPError, why:254- self._build_response(why)255- self.response.error = why256- else:257- self._build_response(resp)258- self.response.ok = True259-260- self.response.cached = False261- else:262- self.response.cached = True263-264- self.sent = self.response.ok265-266- return self.sent267-268-269- def read(self, *args):270- return self.response.read()271-272-273-274-class 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- """279-280- 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 = False288-289-290- def __repr__(self):291- return '<Response [%s]>' % (self.status_code)292-293-294- def __nonzero__(self):295- """Returns true if status_code is 'OK'."""296- return not self.error297-298-299- def raise_for_status(self):300- """Raises stored HTTPError if one exists."""301- if self.error:302- raise self.error303-304- def read(self, *args):305- return self.content306-307-308-309-class AuthManager(object):310- """Authentication Manager."""311-312- def __new__(cls):313- singleton = cls.__dict__.get('__singleton__')314- if singleton is not None:315- return singleton316-317- cls.__singleton__ = singleton = object.__new__(cls)318-319- return singleton320-321-322- def __init__(self):323- self.passwd = {}324- self._auth = {}325-326-327- def __repr__(self):328- return '<AuthManager [%s]>' % (self.method)329-330-331- def add_auth(self, uri, auth):332- """Registers AuthObject to AuthManager."""333-334- uri = self.reduce_uri(uri, False)335-336- # try to make it an AuthObject337- if not isinstance(auth, AuthObject):338- try:339- auth = AuthObject(*auth)340- except TypeError:341- pass342-343- self._auth[uri] = auth344-345-346- 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]351-352- reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])353-354- if reduced_uri not in self.passwd:355- self.passwd[reduced_uri] = {}356- self.passwd[reduced_uri] = (user, passwd)357-358-359- 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 authinfo365-366- return (None, None)367-368-369- def get_auth(self, uri):370- (in_domain, in_path) = self.reduce_uri(uri, False)371-372- 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 authority378-379-380- 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)401-402- return authority, path403-404-405- def is_suburi(self, base, test):406- """Check if test is below base in a URI tree407-408- 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 False418-419-420- def empty(self):421- self.passwd = {}422-423-424- def remove(self, uri, realm=None):425- # uri could be a single URI or a sequence426- if isinstance(uri, basestring):427- uri = [uri]428-429- 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]432-433-434- def __contains__(self, uri):435- # uri could be a single URI or a sequence436- if isinstance(uri, basestring):437- uri = [uri]438-439- uri = tuple([self.reduce_uri(u, False) for u in uri])440-441- if uri in self.passwd:442- return True443-444- return False445-446-auth_manager = AuthManager()447-448-449-450-class 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.455-456- :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- """461-462- _handlers = {463- 'basic': _HTTPBasicAuthHandler,464- 'digest': urllib2.HTTPDigestAuthHandler,465- 'proxy_basic': urllib2.ProxyBasicAuthHandler,466- 'proxy_digest': urllib2.ProxyDigestAuthHandler467- }468-469- def __init__(self, username, password, handler='basic', realm=None):470- self.username = username471- self.password = password472- self.realm = realm473-474- if isinstance(handler, basestring):475- self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)476- else:477- self.handler = handler478-479-480-481-482-def request(method, url, **kwargs):483- """Sends a `method` request. Returns :class:`Response` object.484-485- :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())496-497- 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()502-503- return r.response504-505-506-def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):507- """Sends a GET request. Returns :class:`Response` object.508-509- :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- """516-517- return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)518-519-520-def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):521- """Sends a HEAD request. Returns :class:`Response` object.522-523- :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- """530-531- return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)532-533-534-def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):535- """Sends a POST request. Returns :class:`Response` object.536-537- :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- """545-546- return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)547-548-549-def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):550- """Sends a PUT request. Returns :class:`Response` object.551-552- :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- """560-561- return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)562-563-564-def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):565- """Sends a DELETE request. Returns :class:`Response` object.566-567- :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- """574-575- return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)576-577-578-579-class RequestException(Exception):580- """There was an ambiguous exception that occured while handling your581- request."""582-583-class AuthenticationError(RequestException):584- """The authentication credentials provided were invalid."""585-586-class URLRequired(RequestException):587- """A valid URL is required to make a request."""588-589-class InvalidMethod(RequestException):590- """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, _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+85 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.monkeys5+~~~~~~~~~~~~~~~~6+7+Monkey patches to urllib2 and the like.8+9+"""10+11+# import requests12+# import urllib13+import urllib214+# import socket15+# import zlib16+17+18+class _Request(urllib2.Request):19+ """Hidden wrapper around the urllib2.Request object. Allows for manual20+ setting of HTTP methods.21+ """22+23+ 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 = method26+27+ def get_method(self):28+ if self.method:29+ return self.method30+31+ return urllib2.Request.get_method(self)32+33+34+class _HTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):35+ # from mercurial36+37+ def __init__(self, *args, **kwargs):38+ urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)39+ self.retried_req = None40+41+ 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+ pass46+47+ 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)54+55+56+57+class _HTTPDigestAuthHandler(urllib2.HTTPDigestAuthHandler):58+59+ def __init__(self, *args, **kwargs):60+ urllib2.HTTPDigestAuthHandler.__init__(self, *args, **kwargs)61+ self.retried_req = None62+63+ 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+ pass68+69+ 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.77+78+ 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+ raiseadded:requests/patches.py+5 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.monkeys5+"""modified:test_requests.py+1 added-1 removed
121 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)23 unmodified lines154 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)157- print r.__dict__158 159 160 if __name__ == '__main__':161 unittest.main()