Merge https://github.com/Digitalxero/requests into merge/xero
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 8b3c4da, f96157d · Browse files · 4 files·+300 added−271 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+300 added−271 removed
- other:+300 added−271 removed
Provenance
- Commit
1f60e10- Tree
14c6076- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
8b3c4da- Parent 2
f96157d
4 files changed+300 added−271 removed
added:requests/async.py+43 added
1+# -*- coding: utf-8 -*-2+3+"""4+ requests.core5+ ~~~~~~~~~~~~~6+7+ This module implements the main Requests system.8+9+ :copyright: (c) 2011 by Kenneth Reitz.10+ :license: ISC, see LICENSE for more details.11+"""12+13+from __future__ import absolute_import14+import urllib15+import urllib216+from urllib2 import HTTPError17+18+try:19+ import eventlet20+ eventlet.monkey_patch()21+except ImportError:22+ pass23+24+if not 'eventlet' in locals():25+ try:26+ from gevent import monkey27+ monkey.patch_all()28+ except ImportError:29+ pass30+31+if not 'eventlet' in locals():32+ raise ImportError('No Async adaptations of urllib2 found!')33+34+from .core import *35+36+__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'auth_manager', 'AuthObject',37+ 'RequestException', 'AuthenticationError', 'URLRequired', 'InvalidMethod', 'HTTPError']38+__title__ = 'requests'39+__version__ = '0.0.1'40+__build__ = 0x00000141+__author__ = 'Dj Gilcrease'42+__license__ = 'ISC'43+__copyright__ = 'Copyright 2011 Kenneth Reitz'modified:requests/core.py+225 added-225 removed
11 unmodified lines12 13 from __future__ import absolute_import14 import urllib15 import urllib216-16 from urllib2 import HTTPError17 19-try:20- import eventlet21- eventlet.monkey_patch()22-except ImportError:23- pass24-25-if not 'eventlet' in locals():26- try:27- from gevent import monkey28- monkey.patch_all()29- except ImportError:30- pass31-18 from .packages.poster.encode import multipart_encode19 from .packages.poster.streaminghttp import register_openers20 35-21+__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'auth_manager', 'AuthObject',22+ 'RequestException', 'AuthenticationError', 'URLRequired', 'InvalidMethod', 'HTTPError']23 __title__ = 'requests'37-__version__ = '0.2.4'38-__build__ = 0x00020439-__author__ = 'Kenneth Reitz'24+__version__ = '0.2.5'25+__build__ = 0x00020526+__author__ = 'Kenneth Reitz, Dj Gilcrease'27 __license__ = 'ISC'28 __copyright__ = 'Copyright 2011 Kenneth Reitz'29 43-44-AUTOAUTHS = []45-46-47-30 class _Request(urllib2.Request):31 """Hidden wrapper around the urllib2.Request object. Allows for manual32 setting of HTTP methods.33 """52- 34+35 def __init__(self, url, data=None, headers={}, origin_req_host=None,36 unverifiable=False, method=None):37 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)38 self.method = method8 unmodified lines47 class Request(object):48 """The :class:`Request` object. It carries out all functionality of49 Requests. Recommended interface is with the Requests functions.50 """69- 51+52 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71- 53+54 def __init__(self, url=None, headers=dict(), files=None, method=None,73- params=dict(), data=dict(), auth=None, cookiejar=None):55+ data=dict(), auth=None, cookiejar=None):56 self.url = url57 self.headers = headers58 self.files = files59 self.method = method78- self.params = params79- self.data = data60+61+ # url encode data if it's a dict62+ if isinstance(data, dict):63+ self.data = urllib.urlencode(data)64+ else:65+ self.data = data66+67 self.response = Response()81- 68+69+ if isinstance(auth, (list, tuple)):70+ auth = AuthObject(*auth)71+ if not auth:72+ auth = auth_manager.get_auth(self.url)73 self.auth = auth74 self.cookiejar = cookiejar75 self.sent = False85- 86- 76+77 def __repr__(self):78 return '<Request [%s]>' % (self.method)89- 90- 79+80 def __setattr__(self, name, value):81 if (name == 'method') and (value):82 if not value in self._METHODS:83 raise InvalidMethod()95- 84+85 object.__setattr__(self, name, value)97- 98- 86+87 def _checks(self):88 """Deterministic checks for consistency."""89 90 if not self.url:91 raise URLRequired92 105- 93 def _get_opener(self):94 """Creates appropriate opener object for urllib2."""95 96 _handlers = []97 111- if self.auth or self.cookiejar:98+ if self.auth:99+ if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):100+ auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)101+ self.auth.handler = self.auth.handler(auth_manager)102+ auth_manager.add_auth(self.url, self.auth)103 113- if self.auth:104+ _handlers.append(self.auth.handler)105 115- authr = urllib2.HTTPPasswordMgrWithDefaultRealm()116-117- authr.add_password(None, self.url, self.auth.username, self.auth.password)118- auth_handler = urllib2.HTTPBasicAuthHandler(authr)119-120- _handlers.append(auth_handler)121-122- if self.cookiejar:123-124- cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)125- _handlers.append(cookie_handler)126-106+ if self.cookiejar:107+ cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)108+ _handlers.append(cookie_handler)109+ if _handlers:110 opener = urllib2.build_opener(*_handlers)111 return opener.open129-112 else:113 return urllib2.urlopen114 115 116 def _build_response(self, resp):117 """Build internal Response object from given response."""136- 118+119 self.response.status_code = resp.code138- self.response.headers = resp.info().dict120+ self.response.headers = resp.info().dict or resp.headers121 self.response.content = resp.read()122 self.response.url = resp.url123 142- 124+125 def send(self, anyway=False):126 """Sends the request. Returns True of successful, false if not.127 If there was an HTTPError during transmission,128 self.response.status_code will contain the HTTPError code.2 unmodified lines131 132 :param anyway: If True, request will be sent, even if it has133 already been sent.134 """153-135 self._checks()155-136 success = False137 158-138 if self.method in ('GET', 'HEAD', 'DELETE'):160- if (not self.sent) or anyway:139+ req = _Request(("%s?%s" % (self.url, self.data)), method=self.method)140+ else:141+ if self.files:142+ register_openers()143+ datagen, headers = multipart_encode(self.files)144+ req = _Request(self.url, data=datagen, headers=headers, method=self.method)145+ else:146+ req = _Request(self.url, method=self.method)147 162- # url encode GET params if it's a dict163- if isinstance(self.params, dict):164- params = urllib.urlencode(self.params)165- else:166- params = self.params148+ if self.data:149+ req.data = self.data150 168- req = _Request(("%s?%s" % (self.url, params)), method=self.method)151+ if self.headers:152+ req.headers = self.headers153 170- if self.headers:171- req.headers = self.headers172-154+ if not self.sent or anyway:155+ try:156 opener = self._get_opener()157+ resp = opener(req)158+ except urllib2.HTTPError, why:159+ self._build_response(why)160+ self.response.error = why161+ else:162+ self._build_response(resp)163+ self.response.ok = True164 175- try:176- resp = opener(req)177- self._build_response(resp)178- self.response.ok = True165+ self.response.cached = False166+ else:167+ self.response.cached = True168 180- except urllib2.HTTPError, why:181- self._build_response(why)182- self.response.error = why169 184-185- elif self.method == 'PUT':186- if (not self.sent) or anyway:187-188- if self.files:189- register_openers()190- datagen, headers = multipart_encode(self.files)191- req = _Request(self.url, data=datagen, headers=headers, method='PUT')192-193- if self.headers:194- req.headers.update(self.headers)195-196- else:197-198- req = _Request(self.url, method='PUT')199-200- if self.headers:201- req.headers = self.headers202-203- req.data = self.data204-205- try:206- opener = self._get_opener()207- resp = opener(req)208-209- self._build_response(resp)210- self.response.ok = True211-212- except urllib2.HTTPError, why:213- self._build_response(why)214- self.response.error = why215-216-217- elif self.method == 'POST':218- if (not self.sent) or anyway:219-220- if self.files:221- register_openers()222- datagen, headers = multipart_encode(self.files)223- req = _Request(self.url, data=datagen, headers=headers, method='POST')224-225- if self.headers:226- req.headers.update(self.headers)227- 228- else:229- req = _Request(self.url, method='POST')230- req.headers = self.headers231-232- # url encode form data if it's a dict233- if isinstance(self.data, dict):234- req.data = urllib.urlencode(self.data)235- else:236- req.data = self.data237-238- try:239- opener = self._get_opener()240- resp = opener(req)241-242- self._build_response(resp)243- self.response.ok = True244-245- except urllib2.HTTPError, why:246- self._build_response(why)247- self.response.error = why248- 170 self.sent = self.response.ok250- 171+172 return self.sent252- 173 174+175 class Response(object):176 """The :class:`Request` object. All :class:`Request` objects contain a177 :class:`Request.response <response>` attribute, which is an instance of178 this class.5 unmodified lines184 self.headers = dict()185 self.url = None186 self.ok = False187 self.error = None188+ self.cached = False267- 189+190 def __repr__(self):191 return '<Response [%s]>' % (self.status_code)270- 192+193 def __nonzero__(self):194 """Returns true if status_code is 'OK'."""195 return not self.error274- 196+197 def raise_for_status(self):198 """Raises stored HTTPError if one exists."""199 if self.error:200 raise self.error201 202+class AuthManager(object):203+ def __new__(cls):204+ singleton = cls.__dict__.get('__singleton__')205+ if singleton is not None:206+ return singleton207 208+ cls.__singleton__ = singleton = object.__new__(cls)281- 209+210+ return singleton211+212+ def __init__(self):213+ self.passwd = {}214+ self._auth = {}215+216+ def add_auth(self, uri, auth):217+ uri = self.reduce_uri(uri, False)218+ self._auth[uri] = auth219+220+ def add_password(self, realm, uri, user, passwd):221+ # uri could be a single URI or a sequence222+ if isinstance(uri, basestring):223+ uri = [uri]224+ reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])225+ if reduced_uri not in self.passwd:226+ self.passwd[reduced_uri] = {}227+ self.passwd[reduced_uri] = (user, passwd)228+229+ def find_user_password(self, realm, authuri):230+ for uris, authinfo in self.passwd.iteritems():231+ reduced_authuri = self.reduce_uri(authuri, False)232+ for uri in uris:233+ if self.is_suburi(uri, reduced_authuri):234+ return authinfo235+236+ return (None, None)237+238+ def get_auth(self, uri):239+ uri = self.reduce_uri(uri, False)240+ return self._auth.get(uri, None)241+242+ def reduce_uri(self, uri, default_port=True):243+ """Accept authority or URI and extract only the authority and path."""244+ # note HTTP URLs do not have a userinfo component245+ parts = urllib2.urlparse.urlsplit(uri)246+ if parts[1]:247+ # URI248+ scheme = parts[0]249+ authority = parts[1]250+ path = parts[2] or '/'251+ else:252+ # host or host:port253+ scheme = None254+ authority = uri255+ path = '/'256+ host, port = urllib2.splitport(authority)257+ if default_port and port is None and scheme is not None:258+ dport = {"http": 80,259+ "https": 443,260+ }.get(scheme)261+ if dport is not None:262+ authority = "%s:%d" % (host, dport)263+ return authority, path264+265+ def is_suburi(self, base, test):266+ """Check if test is below base in a URI tree267+268+ Both args must be URIs in reduced form.269+ """270+ if base == test:271+ return True272+ if base[0] != test[0]:273+ return False274+ common = urllib2.posixpath.commonprefix((base[1], test[1]))275+ if len(common) == len(base[1]):276+ return True277+ return False278+279+ def empty(self):280+ self.passwd = {}281+282+ def remove(self, uri, realm=None):283+ # uri could be a single URI or a sequence284+ if isinstance(uri, basestring):285+ uri = [uri]286+287+ for default_port in True, False:288+ reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])289+ del self.passwd[reduced_uri][realm]290+291+ def __contains__(self, uri):292+ # uri could be a single URI or a sequence293+ if isinstance(uri, basestring):294+ uri = [uri]295+296+ uri = tuple([self.reduce_uri(u, False) for u in uri])297+298+ if uri in self.passwd:299+ return True300+301+ return False302+303+auth_manager = AuthManager()304+305+306 class AuthObject(object):307 """The :class:`AuthObject` is a simple HTTP Authentication token. When308 given to a Requests function, it enables Basic HTTP Authentication for that309 Request. You can also enable Authorization for domain realms with AutoAuth.310 See AutoAuth for more details.287- 311+312 :param username: Username to authenticate with.313 :param password: Password for given username.314+ :param realm: (optional) the realm this auth applies to315+ :param handler: (optional) basic || digest || proxy_basic || proxy_digest316 """291- 292- def __init__(self, username, password):317+318+ _handlers = {319+ 'basic': urllib2.HTTPBasicAuthHandler,320+ 'digest': urllib2.HTTPDigestAuthHandler,321+ 'proxy_basic': urllib2.ProxyBasicAuthHandler,322+ 'proxy_digest': urllib2.ProxyDigestAuthHandler323+ }324+325+ def __init__(self, username, password, handler='basic', realm=None):326 self.username = username327 self.password = password328+ self.realm = realm329 330+ if isinstance(handler, basestring):331+ self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)332+ else:333+ self.handler = handler334 335 336+def request(method, url, **kwargs):337+ """Sends a `method` request. Returns :class:`Response` object.338+339+ :param method: method for the new :class:`Request` object.340+ :param url: URL for the new :class:`Request` object.341+ :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.342+ :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.343+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.344+ :param cookies: (optional) CookieJar object to send with the :class:`Request`.345+ :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.346+ :param auth: (optional) AuthObject to enable Basic HTTP Auth.347+ """348+ data = kwargs.pop('data', {}) or kwargs.pop('params', {})349+350+ r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),351+ cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),352+ auth=kwargs.pop('auth', auth_manager.get_auth(url)))353+ r.send()354+355+ return r.response356+357 def get(url, params={}, headers={}, cookies=None, auth=None):358 """Sends a GET request. Returns :class:`Response` object.359 360 :param url: URL for the new :class:`Request` object.1 unmodified line362 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.363 :param cookies: (optional) CookieJar object to send with the :class:`Request`.364 :param auth: (optional) AuthObject to enable Basic HTTP Auth.365 """307- 308- r = Request(method='GET', url=url, params=params, headers=headers,309- cookiejar=cookies, auth=_detect_auth(url, auth))310- r.send()311- 312- return r.response366 367+ return request('GET', url, params=params, headers=headers, cookiejar=cookies, auth=auth)368 369+370 def head(url, params={}, headers={}, cookies=None, auth=None):371 """Sends a HEAD request. Returns :class:`Response` object.372 373 :param url: URL for the new :class:`Request` object.1 unmodified line375 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.376 :param cookies: (optional) CookieJar object to send with the :class:`Request`.377 :param auth: (optional) AuthObject to enable Basic HTTP Auth.378 """324- r = Request(method='HEAD', url=url, params=params, headers=headers,325- cookiejar=cookies, auth=_detect_auth(url, auth))326- r.send()327- 328- return r.response379 380+ return request('HEAD', url, params=params, headers=headers, cookiejar=cookies, auth=auth)381 382+383 def post(url, data={}, headers={}, files=None, cookies=None, auth=None):384 """Sends a POST request. Returns :class:`Response` object.385 386 :param url: URL for the new :class:`Request` object.335- :param data: (optional) Dictionary of POST Data to send with the :class:`Request`.387+ :param data: (optional) Dictionary of POST data to send with the :class:`Request`.388 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.389 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.390 :param cookies: (optional) CookieJar object to send with the :class:`Request`.391 :param auth: (optional) AuthObject to enable Basic HTTP Auth.392 """341- 342- r = Request(method='POST', url=url, data=data, headers=headers,343- files=files, cookiejar=cookies, auth=_detect_auth(url, auth))344- r.send()345- 346- return r.response347- 348- 393+394+ return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)395+396+397 def put(url, data='', headers={}, files={}, cookies=None, auth=None):398 """Sends a PUT request. Returns :class:`Response` object.399 400 :param url: URL for the new :class:`Request` object.353- :param data: (optional) Bytes of PUT Data to send with the :class:`Request`.401+ :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.402 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.403 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.404 :param cookies: (optional) CookieJar object to send with the :class:`Request`.405 :param auth: (optional) AuthObject to enable Basic HTTP Auth.406 """407 360- r = Request(method='PUT', url=url, data=data, headers=headers, files=files,361- cookiejar=cookies, auth=_detect_auth(url, auth))362- r.send()363- 364- return r.response408+ return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)409 366- 410+411 def delete(url, params={}, headers={}, cookies=None, auth=None):412 """Sends a DELETE request. Returns :class:`Response` object.413 414 :param url: URL for the new :class:`Request` object.371- :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.415+ :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.416 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.417 :param cookies: (optional) CookieJar object to send with the :class:`Request`.418 :param auth: (optional) AuthObject to enable Basic HTTP Auth.419 """376- 377- r = Request(method='DELETE', url=url, params=params, headers=headers,378- cookiejar=cookies, auth=_detect_auth(url, auth))379- r.send()380- 381- return r.response420 421+ return request('DELETE', url, params=params, headers=headers, cookiejar=cookies, auth=auth)422 384-def add_autoauth(url, authobject):385- """Registers given AuthObject to given URL domain. for auto-activation.386- Once a URL is registered with an AuthObject, the configured HTTP387- Authentication will be used for all requests with URLS containing the given388- URL string.389-390- Example: ::391- >>> c_auth = requests.AuthObject('kennethreitz', 'xxxxxxx')392- >>> requests.add_autoauth('https://convore.com/api/', c_auth)393- >>> r = requests.get('https://convore.com/api/account/verify.json')394- # Automatically HTTP Authenticated! Wh00t!395-396- :param url: Base URL for given AuthObject to auto-activate for.397- :param authobject: AuthObject to auto-activate.398- """399-400- global AUTOAUTHS401- 402- AUTOAUTHS.append((url, authobject))403-404-405-def _detect_auth(url, auth):406- """Returns registered AuthObject for given url if available, defaulting to407- given AuthObject.408- """409-410- return _get_autoauth(url) if not auth else auth411-412- 413-def _get_autoauth(url):414- """Returns registered AuthObject for given url if available."""415- 416- for (autoauth_url, auth) in AUTOAUTHS:417- if autoauth_url in url: 418- return auth419- 420- return None421-422-423 class RequestException(Exception):424 """There was an ambiguous exception that occured while handling your425 request."""426 427 class AuthenticationError(RequestException):428 """The authentication credentials provided were invalid."""429- 429+430 class URLRequired(RequestException):431 """A valid URL is required to make a request."""432- 432+433 class InvalidMethod(RequestException):434 """An inappropriate method was attempted."""modified:README.rst+24 added-24 removed
1 Requests: The Simple (e.g. usable) HTTP Module2 ==============================================3 4-Most existing Python modules for dealing HTTP requests are insane. I have to look up *everything* that I want to do. Most of my worst Python experiences are a result of the various built-in HTTP libraries (yes, even worse than Logging). 4+Most existing Python modules for dealing HTTP requests are insane. I have to look up *everything* that I want to do. Most of my worst Python experiences are a result of the various built-in HTTP libraries (yes, even worse than Logging).5 6 But this one's different. This one's going to be awesome. And simple.7 8-Really simple. 8+Really simple.9 10 Features11 --------12 1 unmodified line14 + Simple HTTP Header Request Attachment15 + Simple Data/Params Request Attachment16 + Simple Multipart File Uploads17 + CookieJar Support18- 18+19 - Simple Basic HTTP Authentication20 + Simple URL + HTTP Auth Registry21 22 6 unmodified lines29 >>> r = requests.get('http://google.com')30 31 32 HTTPS? Basic Authentication? ::33- 33+34 >>> r = requests.get('https://convore.com/api/account/verify.json')35 >>> r.status_code36 40137 38- 38+39 Uh oh, we're not authorized! Let's add authentication. ::40- 40+41 >>> conv_auth = requests.AuthObject('requeststest', 'requeststest')42 >>> r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)43- 43+44 >>> r.status_code45- 200 46- 45+ 20046+47 >>> r.headers['content-type']48 'application/json'49- 49+50 >>> r.content51 '{"username": "requeststest", "url": "/users/requeststest/", "id": "9408", "img": "censored-long-url"}'52 53 54 55 API56 ---57- 57+58 **Requests:**59 60 All request functions return a Response object (see below).61 62 If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.63 If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.64- 64+65 GET Requests66 >>> request.get(url, params={}, headers={}, cookies=None, auth=None)67 <request object>68- 68+69 HEAD Requests70 >>> request.head(url, params={}, headers={}, cookies=None, auth=None)71 <request object>72- 72+73 PUT Requests74 >>> request.put(url, data='', headers={}, files={}, cookies=None, auth=None)75 <request object>76- 76+77 POST Requests78 >>> request.post(url, data={}, headers={}, files={}, cookies=None, auth=None)79 <request object>80- 80+81 DELETE Requests82 >>> request.delete(url, params={}, headers={}, cookies=None, auth=None)83 <request object>84- 84 85+86 **Responses:**87- 87+88 Response.status_code:89 (Integer) Received HTTP Status Code Response90 91 Response.headers:2 unmodified lines94 Response.content:95 (Bytes) Received Content96 97 Response.url98- (String) URL of response. Useful for detecting redirects. 99- 98+ (String) URL of response. Useful for detecting redirects.99+100 Response.ok101 (Bool) True if no errors occurred during the request, and the status_code is kosher.102- 102+103 Response.error104 (HTTPError) If an HTTPError occurred (e.g. status of 404), Otherwise this is None.105- 105+106 Response.raise_for_status()107 Raises HTTPError if a request is not kosher.108 109 10 unmodified lines120 121 To install requests, simply: ::122 123 $ pip install requests124- 124+125 Or, if you absolutely must: ::126 127 $ easy_install requests128 129 But, you really shouldn't do that.130- 130 131 132+133 Contribute134 ----------135 136 If you'd like to contribute, simply fork `the repository`_, commit your changes to the **develop** branch (or branch off of it), and send a pull request. Make sure you add yourself to AUTHORS_.13 unmodified linesmodified:test_requests.py+8 added-22 removed
6 unmodified lines7 8 9 class RequestsTestSuite(unittest.TestCase):10 """Requests test cases."""11- 11+12 def setUp(self):13 pass14 15 def tearDown(self):16 """Teardown."""17 pass18- 18+19 def test_invalid_url(self):20 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')21 22-22 def test_HTTP_200_OK_GET(self):23 r = requests.get('http://google.com')24 self.assertEqual(r.status_code, 200)25 27-26 def test_HTTPS_200_OK_GET(self):27 r = requests.get('https://google.com')28 self.assertEqual(r.status_code, 200)29 32-30 def test_HTTP_200_OK_HEAD(self):31 r = requests.head('http://google.com')32 self.assertEqual(r.status_code, 200)33 37-34 def test_HTTPS_200_OK_HEAD(self):35 r = requests.head('https://google.com')36 self.assertEqual(r.status_code, 200)37 42-38 def test_AUTH_HTTPS_200_OK_GET(self):44- auth = requests.AuthObject('requeststest', 'requeststest')39+ auth = ('requeststest', 'requeststest')40 url = 'https://convore.com/api/account/verify.json'41 r = requests.get(url, auth=auth)42 43 self.assertEqual(r.status_code, 200)44 50-51- requests.add_autoauth(url, auth)52-45 r = requests.get(url)46 self.assertEqual(r.status_code, 200)47 48 # reset auto authentication57- requests.AUTOAUTHS = []49+ requests.auth_manager.empty()50 59-60-51 def test_POSTBIN_GET_POST_FILES(self):62-63- bin = requests.post('http://www.postbin.org/')52+ bin = requests.get('http://www.postbin.org/')53 self.assertEqual(bin.status_code, 200)54 55 post = requests.post(bin.url, data={'some': 'data'})67- self.assertEqual(post.status_code, 201)56+ self.assertEqual(post.status_code, 200)57 58 post2 = requests.post(bin.url, files={'some': open('test_requests.py')})70- self.assertEqual(post2.status_code, 201)59+ self.assertEqual(post2.status_code, 200)60 72-61 def test_nonzero_evaluation(self):62 r = requests.get('http://google.com/some-404-url')63 self.assertEqual(bool(r), False)76- 64+65 r = requests.get('http://google.com/')66 self.assertEqual(bool(r), True)67 80-68 def test_request_ok_set(self):69 r = requests.get('http://google.com/some-404-url')70 self.assertEqual(r.ok, False)71 85-72 def test_status_raising(self):73 r = requests.get('http://google.com/some-404-url')74 self.assertRaises(requests.HTTPError, r.raise_for_status)75 7 unmodified lines