Skip to content
Myr

Remove the eventles code, this should live in requests.async or something so the user explicitly requests it

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

Clean up the code to get rid of the unnecessary AuthObject class Cleanup the send method Cleanup the convenience methods by adding a request method that they all use.

authored by digitalxero · committed by digitalxero · parent e26570d · Browse files · 2 files+103 added−203 removed
This commit

State

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

Diff stats

2 files+103 added−203 removed

  • other:+103 added−203 removed

2 files+103 added−203 removed

modified:requests/core.py+96 added-184 removed
11 unmodified lines
1213from __future__ import absolute_import14import urllib15import urllib21616from urllib2 import HTTPError1719try:20 import eventlet21 eventlet.monkey_patch()22except ImportError:23 pass2425if not 'eventlet' in locals():26 try:27 from gevent import monkey28 monkey.patch_all()29 except ImportError:30 pass3118from .packages.poster.encode import multipart_encode19from .packages.poster.streaminghttp import register_openers203521__all__ = ['Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 'add_autoauth', 'AUTOAUTHS',22 'RequestException', 'AuthenticationError', 'URLRequired', 'InvalidMethod', 'HTTPError']23__title__ = 'requests'24__version__ = '0.2.4'25__build__ = 0x00020426__author__ = 'Kenneth Reitz'
2 unmodified lines
293031AUTOAUTHS = []32464733class _Request(urllib2.Request):34 """Hidden wrapper around the urllib2.Request object. Allows for manual35 setting of HTTP methods.36 """52 3738 def __init__(self, url, data=None, headers={}, origin_req_host=None,39 unverifiable=False, method=None):40 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)41 self.method = method
8 unmodified lines
50class Request(object):51 """The :class:`Request` object. It carries out all functionality of52 Requests. Recommended interface is with the Requests functions.53 """69 5455 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71 5657 def __init__(self, url=None, headers=dict(), files=None, method=None,73 params=dict(), data=dict(), auth=None, cookiejar=None):58 data=dict(), auth=None, cookiejar=None):59 self.url = url60 self.headers = headers61 self.files = files62 self.method = method78 self.params = params79 self.data = data6364 # url encode data if it's a dict65 if isinstance(data, dict):66 self.data = urllib.urlencode(data)67 else:68 self.data = data6970 self.response = Response()81 7172 self.auth = auth73 self.cookiejar = cookiejar74 self.sent = False85 86 7576 def __repr__(self):77 return '<Request [%s]>' % (self.method)89 90 7879 def __setattr__(self, name, value):80 if (name == 'method') and (value):81 if not value in self._METHODS:82 raise InvalidMethod()95 8384 object.__setattr__(self, name, value)97 98 8586 def _checks(self):87 """Deterministic checks for consistency."""8889 if not self.url:90 raise URLRequired91105 92 def _get_opener(self):93 """Creates appropriate opener object for urllib2."""9495 _handlers = []9697 if self.auth or self.cookiejar:11298 if self.auth:11499 authr = urllib2.HTTPPasswordMgrWithDefaultRealm()100117 authr.add_password(None, self.url, self.auth.username, self.auth.password)101 authr.add_password(None, self.url, self.auth[0], self.auth[1])102 auth_handler = urllib2.HTTPBasicAuthHandler(authr)103104 _handlers.append(auth_handler)105106 if self.cookiejar:123107 cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)108 _handlers.append(cookie_handler)109110 opener = urllib2.build_opener(*_handlers)
4 unmodified lines
115116117 def _build_response(self, resp):118 """Build internal Response object from given response."""136 119120 self.response.status_code = resp.code121 self.response.headers = resp.info().dict122 self.response.content = resp.read()123 self.response.url = resp.url124142 125126 def send(self, anyway=False):127 """Sends the request. Returns True of successful, false if not.128 If there was an HTTPError during transmission,129 self.response.status_code will contain the HTTPError code.
2 unmodified lines
132133 :param anyway: If True, request will be sent, even if it has134 already been sent.135 """153136 self._checks()155137 success = False138158139 if self.method in ('GET', 'HEAD', 'DELETE'):160 if (not self.sent) or anyway:140 req = _Request(("%s?%s" % (self.url, self.data)), method=self.method)141 else:142 if self.files:143 register_openers()144 datagen, headers = multipart_encode(self.files)145 req = _Request(self.url, data=datagen, headers=headers, method=self.method)146 else:147 req = _Request(self.url, method=self.method)148162 # 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.params149 if self.data:150 req.data = self.data151168 req = _Request(("%s?%s" % (self.url, params)), method=self.method)152 if self.headers:153 req.headers = self.headers154170 if self.headers:171 req.headers = self.headers172155 if not self.sent or anyway:156 try:157 opener = self._get_opener()158 resp = opener(req)159 except urllib2.HTTPError, why:160 self._build_response(why)161 self.response.error = why162 else:163 self._build_response(resp)164 self.response.ok = True165 self.response.cached = False166 else:167 self.response.cached = True168175 try:176 resp = opener(req)177 self._build_response(resp)178 self.response.ok = True169180 except urllib2.HTTPError, why:181 self._build_response(why)182 self.response.error = why183184185 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')192193 if self.headers:194 req.headers.update(self.headers)195196 else:197198 req = _Request(self.url, method='PUT')199200 if self.headers:201 req.headers = self.headers202203 req.data = self.data204205 try:206 opener = self._get_opener()207 resp = opener(req)208209 self._build_response(resp)210 self.response.ok = True211212 except urllib2.HTTPError, why:213 self._build_response(why)214 self.response.error = why215216217 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')224225 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.data237238 try:239 opener = self._get_opener()240 resp = opener(req)241242 self._build_response(resp)243 self.response.ok = True244245 except urllib2.HTTPError, why:246 self._build_response(why)247 self.response.error = why248 170 self.sent = self.response.ok250 171172 return self.sent252 173174175class 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 lines
184 self.headers = dict()185 self.url = None186 self.ok = False187 self.error = None188 self.cached = False267 189190 def __repr__(self):191 return '<Response [%s]>' % (self.status_code)270 192193 def __nonzero__(self):194 """Returns true if status_code is 'OK'."""195 return not self.error274 196197 def raise_for_status(self):198 """Raises stored HTTPError if one exists."""199 if self.error:200 raise self.error201202281 282class AuthObject(object):283 """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.203def request(method, url, **kwargs):204 """Sends a `method` request. Returns :class:`Response` object.205206 :param method: method for the new :class:`Request` object.207 :param url: URL for the new :class:`Request` object.208 :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.209 :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.210 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.211 :param cookies: (optional) CookieJar object to send with the :class:`Request`.212 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.213 :param auth: (optional) AuthObject to enable Basic HTTP Auth.214 """291 292 def __init__(self, username, password):293 self.username = username294 self.password = password215 data = kwargs.pop('data', {}) or kwargs.pop('params', {})216217 r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),218 cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),219 auth=_detect_auth(url, kwargs.pop('auth', None)))220 r.send()221222 return r.response223224def get(url, params={}, headers={}, cookies=None, auth=None):225 """Sends a GET request. Returns :class:`Response` object.226
2 unmodified lines
229 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.230 :param cookies: (optional) CookieJar object to send with the :class:`Request`.231 :param auth: (optional) AuthObject to enable Basic HTTP Auth.232 """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.response233234 return request('GET', url, params=params, headers=headers, cookiejar=cookies,235 auth=_detect_auth(url, auth))236237238def head(url, params={}, headers={}, cookies=None, auth=None):239 """Sends a HEAD request. Returns :class:`Response` object.240241 :param url: URL for the new :class:`Request` object.
1 unmodified line
243 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.244 :param cookies: (optional) CookieJar object to send with the :class:`Request`.245 :param auth: (optional) AuthObject to enable Basic HTTP Auth.246 """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.response247248 return request('HEAD', url, params=params, headers=headers, cookiejar=cookies,249 auth=_detect_auth(url, auth))250251252def post(url, data={}, headers={}, files=None, cookies=None, auth=None):253 """Sends a POST request. Returns :class:`Response` object.254255 :param url: URL for the new :class:`Request` object.335 :param data: (optional) Dictionary of POST Data to send with the :class:`Request`.256 :param data: (optional) Dictionary of POST data to send with the :class:`Request`.257 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.258 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.259 :param cookies: (optional) CookieJar object to send with the :class:`Request`.260 :param auth: (optional) AuthObject to enable Basic HTTP Auth.261 """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):262263 return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies,264 auth=_detect_auth(url, auth))265266267def put(url, data=b'', headers={}, files={}, cookies=None, auth=None):268 """Sends a PUT request. Returns :class:`Response` object.269270 :param url: URL for the new :class:`Request` object.353 :param data: (optional) Bytes of PUT Data to send with the :class:`Request`.271 :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.272 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.273 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.274 :param cookies: (optional) CookieJar object to send with the :class:`Request`.275 :param auth: (optional) AuthObject to enable Basic HTTP Auth.276 """277360 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.response278 return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies,279 auth=_detect_auth(url, auth))280366 281282def delete(url, params={}, headers={}, cookies=None, auth=None):283 """Sends a DELETE request. Returns :class:`Response` object.284285 :param url: URL for the new :class:`Request` object.371 :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.286 :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.287 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.288 :param cookies: (optional) CookieJar object to send with the :class:`Request`.289 :param auth: (optional) AuthObject to enable Basic HTTP Auth.290 """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.response291292 return request('DELETE', url, params=params, headers=headers, cookiejar=cookies,293 auth=_detect_auth(url, auth))294295296def add_autoauth(url, authobject):297 """Registers given AuthObject to given URL domain. for auto-activation.298 Once a URL is registered with an AuthObject, the configured HTTP299 Authentication will be used for all requests with URLS containing the given
9 unmodified lines
309 :param authobject: AuthObject to auto-activate.310 """311312 global AUTOAUTHS401 313314 AUTOAUTHS.append((url, authobject))315316317def _detect_auth(url, auth):
2 unmodified lines
320 """321322 return _get_autoauth(url) if not auth else auth323412 324325def _get_autoauth(url):326 """Returns registered AuthObject for given url if available."""415 327328 for (autoauth_url, auth) in AUTOAUTHS:417 if autoauth_url in url: 329 if autoauth_url in url:330 return auth419 331332 return None333334335class RequestException(Exception):
1 unmodified line
337 request."""338339class AuthenticationError(RequestException):340 """The authentication credentials provided were invalid."""429 341342class URLRequired(RequestException):343 """A valid URL is required to make a request."""432 344345class InvalidMethod(RequestException):346 """An inappropriate method was attempted."""
modified:test_requests.py+7 added-19 removed
6 unmodified lines
789class RequestsTestSuite(unittest.TestCase):10 """Requests test cases."""11 1112 def setUp(self):13 pass1415 def tearDown(self):16 """Teardown."""17 pass18 1819 def test_invalid_url(self):20 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')212222 def test_HTTP_200_OK_GET(self):23 r = requests.get('http://google.com')24 self.assertEqual(r.status_code, 200)252726 def test_HTTPS_200_OK_GET(self):27 r = requests.get('https://google.com')28 self.assertEqual(r.status_code, 200)293230 def test_HTTP_200_OK_HEAD(self):31 r = requests.head('http://google.com')32 self.assertEqual(r.status_code, 200)333734 def test_HTTPS_200_OK_HEAD(self):35 r = requests.head('https://google.com')36 self.assertEqual(r.status_code, 200)374238 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)4243 self.assertEqual(r.status_code, 200)445045 requests.add_autoauth(url, auth)4647 r = requests.get(url)48 self.assertEqual(r.status_code, 200)4950 # reset auto authentication51 requests.AUTOAUTHS = []52596053 def test_POSTBIN_GET_POST_FILES(self):6263 bin = requests.post('http://www.postbin.org/')54 bin = requests.get('http://www.postbin.org/')55 self.assertEqual(bin.status_code, 200)5657 post = requests.post(bin.url, data={'some': 'data'})67 self.assertEqual(post.status_code, 201)58 self.assertEqual(post.status_code, 200)5960 post2 = requests.post(bin.url, files={'some': open('test_requests.py')})70 self.assertEqual(post2.status_code, 201)61 self.assertEqual(post2.status_code, 200)627263 def test_nonzero_evaluation(self):64 r = requests.get('http://google.com/some-404-url')65 self.assertEqual(bool(r), False)76 6667 r = requests.get('http://google.com/')68 self.assertEqual(bool(r), True)698070 def test_request_ok_set(self):71 r = requests.get('http://google.com/some-404-url')72 self.assertEqual(r.ok, False)738574 def test_status_raising(self):75 r = requests.get('http://google.com/some-404-url')76 self.assertRaises(requests.HTTPError, r.raise_for_status)77
7 unmodified lines