Skip to content
Myr

Making everyone else happy.

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 015d6b7 · Browse files · 3 files+314 added−314 removed
This commit

State

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

Diff stats

3 files+314 added−314 removed

  • other:+314 added−314 removed

3 files+314 added−314 removed

modified:requests/core.py+233 added-233 removed
15 unmodified lines
1617from urllib2 import HTTPError1819try:20 import eventlet21 eventlet.monkey_patch()20 import eventlet21 eventlet.monkey_patch()22except ImportError:23 pass23 pass2425if not 'eventlet' in locals():26 try:27 from gevent import monkey28 monkey.patch_all()29 except ImportError:30 pass26 try:27 from gevent import monkey28 monkey.patch_all()29 except ImportError:30 pass3132from .packages.poster.encode import multipart_encode33from .packages.poster.streaminghttp import register_openers34
10 unmodified lines
45464748class _Request(urllib2.Request):49 """Hidden wrapper around the urllib2.Request object. Allows for manual49 """Hidden wrapper around the urllib2.Request object. Allows for manual50 setting of HTTP methods.51 """52 53 def __init__(self, url, data=None, headers={}, origin_req_host=None,54 unverifiable=False, method=None):55 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)56 self.method = method52 53 def __init__(self, url, data=None, headers={}, origin_req_host=None,54 unverifiable=False, method=None):55 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)56 self.method = method5758 def get_method(self):59 if self.method:60 return self.method58 def get_method(self):59 if self.method:60 return self.method6162 return urllib2.Request.get_method(self)62 return urllib2.Request.get_method(self)636465class Request(object):66 """The :class:`Request` object. It carries out all functionality of66 """The :class:`Request` object. It carries out all functionality of67 Requests. Recommended interface is with the Requests functions.68 """69 70 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71 72 def __init__(self, url=None, headers=dict(), files=None, method=None,73 params=dict(), data=dict(), auth=None, cookiejar=None):74 self.url = url75 self.headers = headers76 self.files = files77 self.method = method78 self.params = params79 self.data = data80 self.response = Response()81 82 self.auth = auth83 self.cookiejar = cookiejar84 self.sent = False85 86 87 def __repr__(self):88 return '<Request [%s]>' % (self.method)89 90 91 def __setattr__(self, name, value):92 if (name == 'method') and (value):93 if not value in self._METHODS:94 raise InvalidMethod()95 96 object.__setattr__(self, name, value)97 98 99 def _checks(self):100 """Deterministic checks for consistency."""69 70 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71 72 def __init__(self, url=None, headers=dict(), files=None, method=None,73 params=dict(), data=dict(), auth=None, cookiejar=None):74 self.url = url75 self.headers = headers76 self.files = files77 self.method = method78 self.params = params79 self.data = data80 self.response = Response()81 82 self.auth = auth83 self.cookiejar = cookiejar84 self.sent = False85 86 87 def __repr__(self):88 return '<Request [%s]>' % (self.method)89 90 91 def __setattr__(self, name, value):92 if (name == 'method') and (value):93 if not value in self._METHODS:94 raise InvalidMethod()95 96 object.__setattr__(self, name, value)97 98 99 def _checks(self):100 """Deterministic checks for consistency."""101102 if not self.url:103 raise URLRequired102 if not self.url:103 raise URLRequired104105 106 def _get_opener(self):107 """Creates appropriate opener object for urllib2."""105 106 def _get_opener(self):107 """Creates appropriate opener object for urllib2."""108109 _handlers = []109 _handlers = []110111 if self.auth or self.cookiejar:111 if self.auth or self.cookiejar:112113 if self.auth:113 if self.auth:114115 authr = urllib2.HTTPPasswordMgrWithDefaultRealm()115 authr = urllib2.HTTPPasswordMgrWithDefaultRealm()116117 authr.add_password(None, self.url, self.auth.username, self.auth.password)118 auth_handler = urllib2.HTTPBasicAuthHandler(authr)117 authr.add_password(None, self.url, self.auth.username, self.auth.password)118 auth_handler = urllib2.HTTPBasicAuthHandler(authr)119120 _handlers.append(auth_handler)120 _handlers.append(auth_handler)121122 if self.cookiejar:122 if self.cookiejar:123124 cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)125 _handlers.append(cookie_handler)124 cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)125 _handlers.append(cookie_handler)126127 opener = urllib2.build_opener(*_handlers)128 return opener.open127 opener = urllib2.build_opener(*_handlers)128 return opener.open129130 else:131 return urllib2.urlopen130 else:131 return urllib2.urlopen132133134 def _build_response(self, resp):135 """Build internal Response object from given response."""136 137 self.response.status_code = resp.code138 self.response.headers = resp.info().dict139 self.response.content = resp.read()140 self.response.url = resp.url134 def _build_response(self, resp):135 """Build internal Response object from given response."""136 137 self.response.status_code = resp.code138 self.response.headers = resp.info().dict139 self.response.content = resp.read()140 self.response.url = resp.url141142 143 def send(self, anyway=False):144 """Sends the request. Returns True of successful, false if not.142 143 def send(self, anyway=False):144 """Sends the request. Returns True of successful, false if not.145 If there was an HTTPError during transmission,146 self.response.status_code will contain the HTTPError code.147148 Once a request is successfully sent, `sent` will equal True.
1 unmodified line
150 :param anyway: If True, request will be sent, even if it has151 already been sent.152 """153154 self._checks()154 self._checks()155156 success = False156 success = False157158159 if self.method in ('GET', 'HEAD', 'DELETE'):160 if (not self.sent) or anyway:159 if self.method in ('GET', 'HEAD', 'DELETE'):160 if (not self.sent) or anyway:161162 # 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.params162 # 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.params167168 req = _Request(("%s?%s" % (self.url, params)), method=self.method)168 req = _Request(("%s?%s" % (self.url, params)), method=self.method)169170 if self.headers:171 req.headers = self.headers170 if self.headers:171 req.headers = self.headers172173 opener = self._get_opener()173 opener = self._get_opener()174175 try:176 resp = opener(req)177 self._build_response(resp)178 self.response.ok = True175 try:176 resp = opener(req)177 self._build_response(resp)178 self.response.ok = True179180 except urllib2.HTTPError as why:181 self._build_response(why)182 self.response.error = why180 except urllib2.HTTPError as why:181 self._build_response(why)182 self.response.error = why183184185 elif self.method == 'PUT':186 if (not self.sent) or anyway:185 elif self.method == 'PUT':186 if (not self.sent) or anyway:187188 if self.files:189 register_openers()190 datagen, headers = multipart_encode(self.files)191 req = _Request(self.url, data=datagen, headers=headers, method='PUT')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')192193 if self.headers:194 req.headers.update(self.headers)193 if self.headers:194 req.headers.update(self.headers)195196 else:196 else:197198 req = _Request(self.url, method='PUT')198 req = _Request(self.url, method='PUT')199200 if self.headers:201 req.headers = self.headers200 if self.headers:201 req.headers = self.headers202203 req.data = self.data203 req.data = self.data204205 try:206 opener = self._get_opener()207 resp = opener(req)205 try:206 opener = self._get_opener()207 resp = opener(req)208209 self._build_response(resp)210 self.response.ok = True209 self._build_response(resp)210 self.response.ok = True211212 except urllib2.HTTPError as why:213 self._build_response(why)214 self.response.error = why212 except urllib2.HTTPError as why:213 self._build_response(why)214 self.response.error = why215216217 elif self.method == 'POST':218 if (not self.sent) or anyway:217 elif self.method == 'POST':218 if (not self.sent) or anyway:219220 if self.files:221 register_openers()222 datagen, headers = multipart_encode(self.files)223 req = _Request(self.url, data=datagen, headers=headers, method='POST')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')224225 if self.headers:226 req.headers.update(self.headers)227 228 else:229 req = _Request(self.url, method='POST')230 req.headers = self.headers225 if self.headers:226 req.headers.update(self.headers)227 228 else:229 req = _Request(self.url, method='POST')230 req.headers = self.headers231232 # 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.data232 # 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.data237238 try:239 opener = self._get_opener()240 resp = opener(req)238 try:239 opener = self._get_opener()240 resp = opener(req)241242 self._build_response(resp)243 self.response.ok = True242 self._build_response(resp)243 self.response.ok = True244245 except urllib2.HTTPError as why:246 self._build_response(why)247 self.response.error = why248 249 self.sent = self.response.ok250 251 return self.sent252 245 except urllib2.HTTPError as why:246 self._build_response(why)247 self.response.error = why248 249 self.sent = self.response.ok250 251 return self.sent252 253254class Response(object):255 """The :class:`Request` object. All :class:`Request` objects contain a255 """The :class:`Request` object. All :class:`Request` objects contain a256 :class:`Request.response <response>` attribute, which is an instance of257 this class.258 """259260 def __init__(self):261 self.content = None262 self.status_code = None263 self.headers = dict()264 self.url = None265 self.ok = False266 self.error = None267 268 def __repr__(self):269 return '<Response [%s]>' % (self.status_code)270 271 def __nonzero__(self):272 """Returns true if status_code is 'OK'."""273 return not self.error274 275 def raise_for_status(self):276 """Raises stored HTTPError if one exists."""277 if self.error:278 raise self.error260 def __init__(self):261 self.content = None262 self.status_code = None263 self.headers = dict()264 self.url = None265 self.ok = False266 self.error = None267 268 def __repr__(self):269 return '<Response [%s]>' % (self.status_code)270 271 def __nonzero__(self):272 """Returns true if status_code is 'OK'."""273 return not self.error274 275 def raise_for_status(self):276 """Raises stored HTTPError if one exists."""277 if self.error:278 raise self.error279280281 281 282class AuthObject(object):283 """The :class:`AuthObject` is a simple HTTP Authentication token. When283 """The :class:`AuthObject` is a simple HTTP Authentication token. When284 given to a Requests function, it enables Basic HTTP Authentication for that285 Request. You can also enable Authorization for domain realms with AutoAuth.286 See AutoAuth for more details.287 288 :param username: Username to authenticate with.289 :param password: Password for given username.290 """291 292 def __init__(self, username, password):293 self.username = username294 self.password = password291 292 def __init__(self, username, password):293 self.username = username294 self.password = password295296297298def get(url, params={}, headers={}, cookies=None, auth=None):299 """Sends a GET request. Returns :class:`Response` object.299 """Sends a GET request. Returns :class:`Response` object.300301 :param url: URL for the new :class:`Request` object.302 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.303 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.304 :param cookies: (optional) CookieJar object to send with the :class:`Request`.305 :param auth: (optional) AuthObject to enable Basic HTTP Auth.306 """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.response307 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.response313314315def head(url, params={}, headers={}, cookies=None, auth=None):316 """Sends a HEAD request. Returns :class:`Response` object.316 """Sends a HEAD request. Returns :class:`Response` object.317318 :param url: URL for the new :class:`Request` object.319 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.320 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.321 :param cookies: (optional) CookieJar object to send with the :class:`Request`.322 :param auth: (optional) AuthObject to enable Basic HTTP Auth.323 """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.response324 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.response329330331def post(url, data={}, headers={}, files=None, cookies=None, auth=None):332 """Sends a POST request. Returns :class:`Response` object.332 """Sends a POST request. Returns :class:`Response` object.333334 :param url: URL for the new :class:`Request` object.335 :param data: (optional) Dictionary of POST Data to send with the :class:`Request`.336 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.337 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.338 :param cookies: (optional) CookieJar object to send with the :class:`Request`.339 :param auth: (optional) AuthObject to enable Basic HTTP Auth.340 """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 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 349def put(url, data='', headers={}, files={}, cookies=None, auth=None):350 """Sends a PUT request. Returns :class:`Response` object.350 """Sends a PUT request. Returns :class:`Response` object.351352 :param url: URL for the new :class:`Request` object.353 :param data: (optional) Bytes of PUT Data to send with the :class:`Request`.354 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.
1 unmodified line
356 :param cookies: (optional) CookieJar object to send with the :class:`Request`.357 :param auth: (optional) AuthObject to enable Basic HTTP Auth.358 """359360 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.response360 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.response365366 366 367def delete(url, params={}, headers={}, cookies=None, auth=None):368 """Sends a DELETE request. Returns :class:`Response` object.368 """Sends a DELETE request. Returns :class:`Response` object.369370 :param url: URL for the new :class:`Request` object.371 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.372 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.373 :param cookies: (optional) CookieJar object to send with the :class:`Request`.374 :param auth: (optional) AuthObject to enable Basic HTTP Auth.375 """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.response376 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.response382383384def add_autoauth(url, authobject):385 """Registers given AuthObject to given URL domain. for auto-activation.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
6 unmodified lines
396 :param url: Base URL for given AuthObject to auto-activate for.397 :param authobject: AuthObject to auto-activate.398 """399400 global AUTOAUTHS401 402 AUTOAUTHS.append((url, authobject))400 global AUTOAUTHS401 402 AUTOAUTHS.append((url, authobject))403404405def _detect_auth(url, auth):406 """Returns registered AuthObject for given url if available, defaulting to406 """Returns registered AuthObject for given url if available, defaulting to407 given AuthObject.408 """409410 return _get_autoauth(url) if not auth else auth410 return _get_autoauth(url) if not auth else auth411412 412 413def _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 None414 """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 None421422423class RequestException(Exception):424 """There was an ambiguous exception that occured while handling your424 """There was an ambiguous exception that occured while handling your425 request."""426427class AuthenticationError(RequestException):428 """The authentication credentials provided were invalid."""429 428 """The authentication credentials provided were invalid."""429 430class URLRequired(RequestException):431 """A valid URL is required to make a request."""432 431 """A valid URL is required to make a request."""432 433class InvalidMethod(RequestException):434 """An inappropriate method was attempted."""434 """An inappropriate method was attempted."""
modified:setup.py+31 added-31 removed
5 unmodified lines
67from distutils.core import setup8910 10 11if sys.argv[-1] == "publish":12 os.system("python setup.py sdist upload")13 sys.exit()12 os.system("python setup.py sdist upload")13 sys.exit()1415if sys.argv[-1] == "test":16 os.system("python test_requests.py")17 sys.exit()18 16 os.system("python test_requests.py")17 sys.exit()18 19required = []2021# if python > 2.6, require simplejson2223setup(24 name='requests',25 version='0.2.3',26 description='Awesome Python HTTP Library that\'s actually usable.',27 long_description=open('README.rst').read() + '\n\n' +28 open('HISTORY.rst').read(),29 author='Kenneth Reitz',30 author_email='me@kennethreitz.com',31 url='https://github.com/kennethreitz/requests',32 packages= [33 'requests',34 'requests.packages',35 'requests.packages.poster'36 ],37 install_requires=required,38 license='ISC',39 classifiers=(40 # 'Development Status :: 5 - Production/Stable',41 'Intended Audience :: Developers',42 'Natural Language :: English',43 'License :: OSI Approved :: ISC License (ISCL)',44 'Programming Language :: Python',24 name='requests',25 version='0.2.3',26 description='Awesome Python HTTP Library that\'s actually usable.',27 long_description=open('README.rst').read() + '\n\n' +28 open('HISTORY.rst').read(),29 author='Kenneth Reitz',30 author_email='me@kennethreitz.com',31 url='https://github.com/kennethreitz/requests',32 packages= [33 'requests',34 'requests.packages',35 'requests.packages.poster'36 ],37 install_requires=required,38 license='ISC',39 classifiers=(40 # 'Development Status :: 5 - Production/Stable',41 'Intended Audience :: Developers',42 'Natural Language :: English',43 'License :: OSI Approved :: ISC License (ISCL)',44 'Programming Language :: Python',45 # 'Programming Language :: Python :: 2.5',46 'Programming Language :: Python :: 2.6',47 'Programming Language :: Python :: 2.7',48 # 'Programming Language :: Python :: 3.0',49 # 'Programming Language :: Python :: 3.1',50 ),47 'Programming Language :: Python :: 2.7',48 # 'Programming Language :: Python :: 3.0',49 # 'Programming Language :: Python :: 3.1',50 ),51)
modified:test_requests.py+50 added-50 removed
6 unmodified lines
7import requests8910class RequestsTestSuite(unittest.TestCase):11 """Requests test cases."""12 13 def setUp(self):14 pass11 """Requests test cases."""12 13 def setUp(self):14 pass1516 def tearDown(self):17 """Teardown."""18 pass19 20 def test_invalid_url(self):21 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')16 def tearDown(self):17 """Teardown."""18 pass19 20 def test_invalid_url(self):21 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')222324 def test_HTTP_200_OK_GET(self):25 r = requests.get('http://google.com')26 self.assertEqual(r.status_code, 200)24 def test_HTTP_200_OK_GET(self):25 r = requests.get('http://google.com')26 self.assertEqual(r.status_code, 200)272829 def test_HTTPS_200_OK_GET(self):30 r = requests.get('https://google.com')31 self.assertEqual(r.status_code, 200)29 def test_HTTPS_200_OK_GET(self):30 r = requests.get('https://google.com')31 self.assertEqual(r.status_code, 200)323334 def test_HTTP_200_OK_HEAD(self):35 r = requests.head('http://google.com')36 self.assertEqual(r.status_code, 200)34 def test_HTTP_200_OK_HEAD(self):35 r = requests.head('http://google.com')36 self.assertEqual(r.status_code, 200)373839 def test_HTTPS_200_OK_HEAD(self):40 r = requests.head('https://google.com')41 self.assertEqual(r.status_code, 200)39 def test_HTTPS_200_OK_HEAD(self):40 r = requests.head('https://google.com')41 self.assertEqual(r.status_code, 200)424344 def test_AUTH_HTTPS_200_OK_GET(self):45 auth = requests.AuthObject('requeststest', 'requeststest')46 url = 'https://convore.com/api/account/verify.json'47 r = requests.get(url, auth=auth)44 def test_AUTH_HTTPS_200_OK_GET(self):45 auth = requests.AuthObject('requeststest', 'requeststest')46 url = 'https://convore.com/api/account/verify.json'47 r = requests.get(url, auth=auth)4849 self.assertEqual(r.status_code, 200)49 self.assertEqual(r.status_code, 200)505152 def test_POSTBIN_GET_POST_FILES(self):52 def test_POSTBIN_GET_POST_FILES(self):5354 bin = requests.post('http://www.postbin.org/')55 self.assertEqual(bin.status_code, 200)54 bin = requests.post('http://www.postbin.org/')55 self.assertEqual(bin.status_code, 200)5657 post = requests.post(bin.url, data={'some': 'data'})58 self.assertEqual(post.status_code, 201)57 post = requests.post(bin.url, data={'some': 'data'})58 self.assertEqual(post.status_code, 201)5960 post2 = requests.post(bin.url, files={'some': StringIO('data')})61 self.assertEqual(post2.status_code, 201)60 post2 = requests.post(bin.url, files={'some': StringIO('data')})61 self.assertEqual(post2.status_code, 201)626364 def test_nonzero_evaluation(self):65 r = requests.get('http://google.com/some-404-url')66 self.assertEqual(bool(r), False)67 68 r = requests.get('http://google.com/')69 self.assertEqual(bool(r), True)64 def test_nonzero_evaluation(self):65 r = requests.get('http://google.com/some-404-url')66 self.assertEqual(bool(r), False)67 68 r = requests.get('http://google.com/')69 self.assertEqual(bool(r), True)707172 def test_request_ok_set(self):73 r = requests.get('http://google.com/some-404-url')74 self.assertEqual(r.ok, False)72 def test_request_ok_set(self):73 r = requests.get('http://google.com/some-404-url')74 self.assertEqual(r.ok, False)757677 def test_status_raising(self):78 r = requests.get('http://google.com/some-404-url')79 self.assertRaises(requests.HTTPError, r.raise_for_status)77 def test_status_raising(self):78 r = requests.get('http://google.com/some-404-url')79 self.assertRaises(requests.HTTPError, r.raise_for_status)8081 r = requests.get('http://google.com/')82 self.assertFalse(r.error)83 r.raise_for_status()81 r = requests.get('http://google.com/')82 self.assertFalse(r.error)83 r.raise_for_status()848586if __name__ == '__main__':87 unittest.main()87 unittest.main()