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
Provenance
- Commit
d1c8933- Tree
ade3b2f- Author
digitalxero <none@none>- Committer
digitalxero <none@none>- Parent
e26570d
2 files changed+103 added−203 removed
modified:requests/core.py+96 added-184 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', '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 lines29 30 31 AUTOAUTHS = []32 46-47-33 class _Request(urllib2.Request):34 """Hidden wrapper around the urllib2.Request object. Allows for manual35 setting of HTTP methods.36 """52- 37+38 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 = method8 unmodified lines50 class Request(object):51 """The :class:`Request` object. It carries out all functionality of52 Requests. Recommended interface is with the Requests functions.53 """69- 54+55 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71- 56+57 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 = data63+64+ # url encode data if it's a dict65+ if isinstance(data, dict):66+ self.data = urllib.urlencode(data)67+ else:68+ self.data = data69+70 self.response = Response()81- 71+72 self.auth = auth73 self.cookiejar = cookiejar74 self.sent = False85- 86- 75+76 def __repr__(self):77 return '<Request [%s]>' % (self.method)89- 90- 78+79 def __setattr__(self, name, value):80 if (name == 'method') and (value):81 if not value in self._METHODS:82 raise InvalidMethod()95- 83+84 object.__setattr__(self, name, value)97- 98- 85+86 def _checks(self):87 """Deterministic checks for consistency."""88 89 if not self.url:90 raise URLRequired91 105- 92 def _get_opener(self):93 """Creates appropriate opener object for urllib2."""94 95 _handlers = []96 97 if self.auth or self.cookiejar:112-98 if self.auth:114-99 authr = urllib2.HTTPPasswordMgrWithDefaultRealm()100 117- 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)103 104 _handlers.append(auth_handler)105 106 if self.cookiejar:123-107 cookie_handler = urllib2.HTTPCookieProcessor(cookiejar)108 _handlers.append(cookie_handler)109 110 opener = urllib2.build_opener(*_handlers)4 unmodified lines115 116 117 def _build_response(self, resp):118 """Build internal Response object from given response."""136- 119+120 self.response.status_code = resp.code121 self.response.headers = resp.info().dict122 self.response.content = resp.read()123 self.response.url = resp.url124 142- 125+126 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 lines132 133 :param anyway: If True, request will be sent, even if it has134 already been sent.135 """153-136 self._checks()155-137 success = False138 158-139 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)148 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.params149+ if self.data:150+ req.data = self.data151 168- req = _Request(("%s?%s" % (self.url, params)), method=self.method)152+ if self.headers:153+ req.headers = self.headers154 170- if self.headers:171- req.headers = self.headers172-155+ 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 = True168 175- try:176- resp = opener(req)177- self._build_response(resp)178- self.response.ok = True169 180- except urllib2.HTTPError, why:181- self._build_response(why)182- self.response.error = why183-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 281- 282-class 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.203+def request(method, url, **kwargs):204+ """Sends a `method` request. Returns :class:`Response` object.205+206+ :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', {})216 217+ 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()221 222+ return r.response223 224 def get(url, params={}, headers={}, cookies=None, auth=None):225 """Sends a GET request. Returns :class:`Response` object.226 2 unmodified lines229 :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.response233 234+ return request('GET', url, params=params, headers=headers, cookiejar=cookies,235+ auth=_detect_auth(url, auth))236 237+238 def head(url, params={}, headers={}, cookies=None, auth=None):239 """Sends a HEAD request. Returns :class:`Response` object.240 241 :param url: URL for the new :class:`Request` object.1 unmodified line243 :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.response247 248+ return request('HEAD', url, params=params, headers=headers, cookiejar=cookies,249+ auth=_detect_auth(url, auth))250 251+252 def post(url, data={}, headers={}, files=None, cookies=None, auth=None):253 """Sends a POST request. Returns :class:`Response` object.254 255 :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- 349-def put(url, data='', headers={}, files={}, cookies=None, auth=None):262+263+ return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies,264+ auth=_detect_auth(url, auth))265+266+267+def put(url, data=b'', headers={}, files={}, cookies=None, auth=None):268 """Sends a PUT request. Returns :class:`Response` object.269 270 :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 """277 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.response278+ return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies,279+ auth=_detect_auth(url, auth))280 366- 281+282 def delete(url, params={}, headers={}, cookies=None, auth=None):283 """Sends a DELETE request. Returns :class:`Response` object.284 285 :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.response291 292+ return request('DELETE', url, params=params, headers=headers, cookiejar=cookies,293+ auth=_detect_auth(url, auth))294 295+296 def 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 given9 unmodified lines309 :param authobject: AuthObject to auto-activate.310 """311 312 global AUTOAUTHS401- 313+314 AUTOAUTHS.append((url, authobject))315 316 317 def _detect_auth(url, auth):2 unmodified lines320 """321 322 return _get_autoauth(url) if not auth else auth323 412- 324+325 def _get_autoauth(url):326 """Returns registered AuthObject for given url if available."""415- 327+328 for (autoauth_url, auth) in AUTOAUTHS:417- if autoauth_url in url: 329+ if autoauth_url in url:330 return auth419- 331+332 return None333 334 335 class RequestException(Exception):1 unmodified line337 request."""338 339 class AuthenticationError(RequestException):340 """The authentication credentials provided were invalid."""429- 341+342 class URLRequired(RequestException):343 """A valid URL is required to make a request."""432- 344+345 class InvalidMethod(RequestException):346 """An inappropriate method was attempted."""modified:test_requests.py+7 added-19 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-45 requests.add_autoauth(url, auth)46 47 r = requests.get(url)48 self.assertEqual(r.status_code, 200)49 50 # reset auto authentication51 requests.AUTOAUTHS = []52 59-60-53 def test_POSTBIN_GET_POST_FILES(self):62-63- bin = requests.post('http://www.postbin.org/')54+ bin = requests.get('http://www.postbin.org/')55 self.assertEqual(bin.status_code, 200)56 57 post = requests.post(bin.url, data={'some': 'data'})67- self.assertEqual(post.status_code, 201)58+ self.assertEqual(post.status_code, 200)59 60 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)62 72-63 def test_nonzero_evaluation(self):64 r = requests.get('http://google.com/some-404-url')65 self.assertEqual(bool(r), False)76- 66+67 r = requests.get('http://google.com/')68 self.assertEqual(bool(r), True)69 80-70 def test_request_ok_set(self):71 r = requests.get('http://google.com/some-404-url')72 self.assertEqual(r.ok, False)73 85-74 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