Merge branch 'release/0.3.0'
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, f8032e0 · Browse files · 8 files·+428 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
8 files+428 added−271 removed
- other:+428 added−271 removed
Provenance
- Commit
044252e- Tree
25b0f3a- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
8b3c4da- Parent 2
f8032e0
8 files changed+428 added−271 removed
modified:requests/packages/poster/streaminghttp.py+7 added-5 removed
179 unmodified lines180 "No Content-Length specified for iterable body")181 return urllib2.HTTPSHandler.do_request_(self, req)182 183 184+def get_handlers():185+ handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]186+ if hasattr(httplib, "HTTPS"):187+ handlers.append(StreamingHTTPSHandler)188+ return handlers189+ 190 def register_openers():191 """Register the streaming http handlers in the global urllib2 default192 opener object.193 194 Returns the created OpenerDirector object."""189- handlers = [StreamingHTTPHandler, StreamingHTTPRedirectHandler]190- if hasattr(httplib, "HTTPS"):191- handlers.append(StreamingHTTPSHandler)195+ opener = urllib2.build_opener(*get_handlers())196 193- opener = urllib2.build_opener(*handlers)194-197 urllib2.install_opener(opener)198 199 return openeradded:requests/async.py+48 added
1+# -*- coding: utf-8 -*-2+3+"""4+ requests.async5+ ~~~~~~~~~~~~~~6+7+ This module implements the main Requests system, after monkey-patching8+ the urllib2 module with eventlet or gevent..9+10+ :copyright: (c) 2011 by Kenneth Reitz.11+ :license: ISC, see LICENSE for more details.12+"""13+14+15+from __future__ import absolute_import16+17+import urllib18+import urllib219+20+from urllib2 import HTTPError21+22+23+try:24+ import eventlet25+ eventlet.monkey_patch()26+except ImportError:27+ pass28+29+if not 'eventlet' in locals():30+ try:31+ from gevent import monkey32+ monkey.patch_all()33+ except ImportError:34+ pass35+36+37+if not 'eventlet' in locals():38+ raise ImportError('No Async adaptations of urllib2 found!')39+40+41+from .core import *42+43+44+__all__ = [45+ 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 46+ 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError', 47+ 'URLRequired', 'InvalidMethod', 'HTTPError'48+]modified:requests/core.py+278 added-217 removed
9 unmodified lines10 :license: ISC, see LICENSE for more details.11 """12 13 from __future__ import absolute_import14+15 import urllib16 import urllib217 18 from urllib2 import HTTPError19+from urlparse import urlparse20 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-21 from .packages.poster.encode import multipart_encode33-from .packages.poster.streaminghttp import register_openers22+from .packages.poster.streaminghttp import register_openers, get_handlers23 24 25+26 __title__ = 'requests'37-__version__ = '0.2.4'38-__build__ = 0x00020427+__version__ = '0.3.0'28+__build__ = 0x00030029 __author__ = 'Kenneth Reitz'30 __license__ = 'ISC'31 __copyright__ = 'Copyright 2011 Kenneth Reitz'32 33+__all__ = [34+ 'Request', 'Response', 'request', 'get', 'head', 'post', 'put', 'delete', 35+ 'auth_manager', 'AuthObject','RequestException', 'AuthenticationError', 36+ 'URLRequired', 'InvalidMethod', 'HTTPError'37+]38 44-AUTOAUTHS = []39 40 47-41 class _Request(urllib2.Request):42 """Hidden wrapper around the urllib2.Request object. Allows for manual43 setting of HTTP methods.44 """52- 53- def __init__(self, url, data=None, headers={}, origin_req_host=None,54- unverifiable=False, method=None):45+46+ def __init__(self, url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None):47 urllib2.Request.__init__(self, url, data, headers, origin_req_host, unverifiable)48 self.method = method49 50 def get_method(self):6 unmodified lines57 class Request(object):58 """The :class:`Request` object. It carries out all functionality of59 Requests. Recommended interface is with the Requests functions.60 """69- 61+62 _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')71- 63+64 def __init__(self, url=None, headers=dict(), files=None, method=None,73- params=dict(), data=dict(), auth=None, cookiejar=None):65+ data=dict(), auth=None, cookiejar=None):66+ 67 self.url = url68 self.headers = headers69 self.files = files70 self.method = method78- self.params = params71 self.data = data72+73+ # url encode data if it's a dict74+ if hasattr(data, 'items'):75+ self._enc_data = urllib.urlencode(data)76+ else:77+ self._enc_data = data78+79 self.response = Response()81- 80+81+ if isinstance(auth, (list, tuple)):82+ auth = AuthObject(*auth)83+ if not auth:84+ auth = auth_manager.get_auth(self.url)85 self.auth = auth86 self.cookiejar = cookiejar87 self.sent = False85- 86- 88+89+90 def __repr__(self):91 return '<Request [%s]>' % (self.method)89- 90- 92+93+94 def __setattr__(self, name, value):95 if (name == 'method') and (value):96 if not value in self._METHODS:97 raise InvalidMethod()95- 98+99 object.__setattr__(self, name, value)97- 98- 100+101+102 def _checks(self):103 """Deterministic checks for consistency."""104 105 if not self.url:106 raise URLRequired107 105- 108+109 def _get_opener(self):110 """Creates appropriate opener object for urllib2."""111 112 _handlers = []113 111- if self.auth or self.cookiejar:114+ if self.auth:115+ if not isinstance(self.auth.handler, (urllib2.AbstractBasicAuthHandler, urllib2.AbstractDigestAuthHandler)):116+ auth_manager.add_password(self.auth.realm, self.url, self.auth.username, self.auth.password)117+ self.auth.handler = self.auth.handler(auth_manager)118+ auth_manager.add_auth(self.url, self.auth)119 113- if self.auth:120+ _handlers.append(self.auth.handler)121 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-122+ _handlers.extend(get_handlers())123 opener = urllib2.build_opener(*_handlers)124 return opener.open129-125 else:126 return urllib2.urlopen127 128 129 def _build_response(self, resp):130 """Build internal Response object from given response."""131 137- self.response.status_code = resp.code138- self.response.headers = resp.info().dict132+ self.response.status_code = getattr(resp, 'code', None)133+ self.response.headers = getattr(resp.info(), 'dict', None)134+ self.response.url = getattr(resp, 'url', None)135 self.response.content = resp.read()140- self.response.url = resp.url136 142- 137+138+ @staticmethod139+ def _build_url(url, data):140+ """Build URLs."""141+ 142+ if urlparse(url).query:143+ return '%s&%s' % (url, data)144+ else:145+ if data:146+ return '%s?%s' % (url, data)147+ else:148+ return url149+150+151 def send(self, anyway=False):152 """Sends the request. Returns True of successful, false if not.153 If there was an HTTPError during transmission,154 self.response.status_code will contain the HTTPError code.2 unmodified lines157 158 :param anyway: If True, request will be sent, even if it has159 already been sent.160 """153-161 self._checks()155-162 success = False163 158-164 if self.method in ('GET', 'HEAD', 'DELETE'):160- if (not self.sent) or anyway:165+ req = _Request(self._build_url(self.url, self._enc_data), method=self.method)166+ else:167 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.params168+ if self.files:169+ register_openers()170 171+ if self.data:172+ self.files.update(self.data)173+ 174+ datagen, headers = multipart_encode(self.files)175+ req = _Request(self.url, data=datagen, headers=headers, method=self.method)176+ 177+ else:168- req = _Request(("%s?%s" % (self.url, params)), method=self.method)178+ req = _Request(self.url, data=self._enc_data, method=self.method)179 170- if self.headers:171- req.headers = self.headers180+ if self.headers:181+ req.headers = self.headers182 183+ if not self.sent or anyway:184+ try:185 opener = self._get_opener()186+ resp = opener(req)187+ except urllib2.HTTPError, why:188+ self._build_response(why)189+ self.response.error = why190+ else:191+ self._build_response(resp)192+ self.response.ok = True193 175- try:176- resp = opener(req)177- self._build_response(resp)178- self.response.ok = True194+ self.response.cached = False195+ else:196+ self.response.cached = True197 180- except urllib2.HTTPError, why:181- self._build_response(why)182- self.response.error = why198 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- 199 self.sent = self.response.ok250- 200+201 return self.sent252- 202 203+204+ 205 class Response(object):206 """The :class:`Request` object. All :class:`Request` objects contain a207 :class:`Request.response <response>` attribute, which is an instance of208 this class.5 unmodified lines214 self.headers = dict()215 self.url = None216 self.ok = False217 self.error = None218+ self.cached = False267- 219+220+221 def __repr__(self):222 return '<Response [%s]>' % (self.status_code)270- 223+224+225 def __nonzero__(self):226 """Returns true if status_code is 'OK'."""227 return not self.error274- 228+229+230 def raise_for_status(self):231 """Raises stored HTTPError if one exists."""232 if self.error:233 raise self.error234 235 236+237+class AuthManager(object):238+ """Authentication Manager."""239 240+ def __new__(cls):241+ singleton = cls.__dict__.get('__singleton__')242+ if singleton is not None:243+ return singleton244+245+ cls.__singleton__ = singleton = object.__new__(cls)246+247+ return singleton248+249+250+ def __init__(self):251+ self.passwd = {}252+ self._auth = {}253+254+255+ def __repr__(self):256+ return '<AuthManager [%s]>' % (self.method)257+258+259+ def add_auth(self, uri, auth):260+ """Registers AuthObject to AuthManager."""261+ 262+ uri = self.reduce_uri(uri, False)263+ self._auth[uri] = auth264+265+ def add_password(self, realm, uri, user, passwd):266+ """Adds password to AuthManager."""267+ # uri could be a single URI or a sequence268+ if isinstance(uri, basestring):269+ uri = [uri]270+ 271+ reduced_uri = tuple([self.reduce_uri(u, False) for u in uri])272+ 273+ if reduced_uri not in self.passwd:274+ self.passwd[reduced_uri] = {}275+ self.passwd[reduced_uri] = (user, passwd)276+277+278+ def find_user_password(self, realm, authuri):279+ for uris, authinfo in self.passwd.iteritems():280+ reduced_authuri = self.reduce_uri(authuri, False)281+ for uri in uris:282+ if self.is_suburi(uri, reduced_authuri):283+ return authinfo284+285+ return (None, None)286+287+288+ def get_auth(self, uri):289+ uri = self.reduce_uri(uri, False)290+ return self._auth.get(uri, None)291+292+293+ def reduce_uri(self, uri, default_port=True):294+ """Accept authority or URI and extract only the authority and path."""295+ # note HTTP URLs do not have a userinfo component296+ parts = urllib2.urlparse.urlsplit(uri)297+ if parts[1]:298+ # URI299+ scheme = parts[0]300+ authority = parts[1]301+ path = parts[2] or '/'302+ else:303+ # host or host:port304+ scheme = None305+ authority = uri306+ path = '/'307+ host, port = urllib2.splitport(authority)308+ if default_port and port is None and scheme is not None:309+ dport = {"http": 80,310+ "https": 443,311+ }.get(scheme)312+ if dport is not None:313+ authority = "%s:%d" % (host, dport)314+ return authority, path315+316+ 317+ def is_suburi(self, base, test):318+ """Check if test is below base in a URI tree319+320+ Both args must be URIs in reduced form.321+ """322+ if base == test:323+ return True324+ if base[0] != test[0]:325+ return False326+ common = urllib2.posixpath.commonprefix((base[1], test[1]))327+ if len(common) == len(base[1]):328+ return True329+ return False330+331+332+ def empty(self):333+ self.passwd = {}334+335+336+ def remove(self, uri, realm=None):337+ # uri could be a single URI or a sequence338+ if isinstance(uri, basestring):339+ uri = [uri]340+341+ for default_port in True, False:342+ reduced_uri = tuple([self.reduce_uri(u, default_port) for u in uri])343+ del self.passwd[reduced_uri][realm]344+345+346+ def __contains__(self, uri):347+ # uri could be a single URI or a sequence348+ if isinstance(uri, basestring):349+ uri = [uri]350+351+ uri = tuple([self.reduce_uri(u, False) for u in uri])352+353+ if uri in self.passwd:354+ return True355+356+ return False357+358+auth_manager = AuthManager()359+360+361+362 class AuthObject(object):363 """The :class:`AuthObject` is a simple HTTP Authentication token. When364 given to a Requests function, it enables Basic HTTP Authentication for that365 Request. You can also enable Authorization for domain realms with AutoAuth.366 See AutoAuth for more details.287- 367+368 :param username: Username to authenticate with.369 :param password: Password for given username.370+ :param realm: (optional) the realm this auth applies to371+ :param handler: (optional) basic || digest || proxy_basic || proxy_digest372 """291- 292- def __init__(self, username, password):373+374+ _handlers = {375+ 'basic': urllib2.HTTPBasicAuthHandler,376+ 'digest': urllib2.HTTPDigestAuthHandler,377+ 'proxy_basic': urllib2.ProxyBasicAuthHandler,378+ 'proxy_digest': urllib2.ProxyDigestAuthHandler379+ }380+381+ def __init__(self, username, password, handler='basic', realm=None):382 self.username = username383 self.password = password384+ self.realm = realm385 386+ if isinstance(handler, basestring):387+ self.handler = self._handlers.get(handler.lower(), urllib2.HTTPBasicAuthHandler)388+ else:389+ self.handler = handler390 391 392+393+394+def request(method, url, **kwargs):395+ """Sends a `method` request. Returns :class:`Response` object.396+397+ :param method: method for the new :class:`Request` object.398+ :param url: URL for the new :class:`Request` object.399+ :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.400+ :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.401+ :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.402+ :param cookies: (optional) CookieJar object to send with the :class:`Request`.403+ :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.404+ :param auth: (optional) AuthObject to enable Basic HTTP Auth.405+ """406+ data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())407+408+ r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', {}),409+ cookiejar=kwargs.pop('cookies', None), files=kwargs.pop('files', None),410+ auth=kwargs.pop('auth', auth_manager.get_auth(url)))411+ r.send()412+413+ return r.response414+415+416 def get(url, params={}, headers={}, cookies=None, auth=None):417 """Sends a GET request. Returns :class:`Response` object.418 419 :param url: URL for the new :class:`Request` object.2 unmodified lines422 :param cookies: (optional) CookieJar object to send with the :class:`Request`.423 :param auth: (optional) AuthObject to enable Basic HTTP Auth.424 """425 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.response426+ return request('GET', url, params=params, headers=headers, cookiejar=cookies, auth=auth)427 428 429 def head(url, params={}, headers={}, cookies=None, auth=None):430 """Sends a HEAD request. Returns :class:`Response` object.3 unmodified lines434 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.435 :param cookies: (optional) CookieJar object to send with the :class:`Request`.436 :param auth: (optional) AuthObject to enable Basic HTTP Auth.437 """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.response438 439+ return request('HEAD', url, params=params, headers=headers, cookiejar=cookies, auth=auth)440 441+442 def post(url, data={}, headers={}, files=None, cookies=None, auth=None):443 """Sends a POST request. Returns :class:`Response` object.444 445 :param url: URL for the new :class:`Request` object.335- :param data: (optional) Dictionary of POST Data to send with the :class:`Request`.446+ :param data: (optional) Dictionary of POST data to send with the :class:`Request`.447 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.448 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.449 :param cookies: (optional) CookieJar object to send with the :class:`Request`.450 :param auth: (optional) AuthObject to enable Basic HTTP Auth.451 """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- 452+453+ return request('POST', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)454+455+456 def put(url, data='', headers={}, files={}, cookies=None, auth=None):457 """Sends a PUT request. Returns :class:`Response` object.458 459 :param url: URL for the new :class:`Request` object.353- :param data: (optional) Bytes of PUT Data to send with the :class:`Request`.460+ :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.461 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.462 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.463 :param cookies: (optional) CookieJar object to send with the :class:`Request`.464 :param auth: (optional) AuthObject to enable Basic HTTP Auth.465 """466 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.response467+ return request('PUT', url, data=data, headers=headers, files=files, cookiejar=cookies, auth=auth)468 366- 469+470 def delete(url, params={}, headers={}, cookies=None, auth=None):471 """Sends a DELETE request. Returns :class:`Response` object.472 473 :param url: URL for the new :class:`Request` object.371- :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.474+ :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.475 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.476 :param cookies: (optional) CookieJar object to send with the :class:`Request`.477 :param auth: (optional) AuthObject to enable Basic HTTP Auth.478 """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.response479 480+ return request('DELETE', url, params=params, headers=headers, cookiejar=cookies, auth=auth)481 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.482 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!483 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-484 class RequestException(Exception):485 """There was an ambiguous exception that occured while handling your486 request."""487 488 class AuthenticationError(RequestException):489 """The authentication credentials provided were invalid."""429- 490+491 class URLRequired(RequestException):492 """A valid URL is required to make a request."""432- 493+494 class InvalidMethod(RequestException):495 """An inappropriate method was attempted."""modified:AUTHORS+2 added
10 unmodified lines11 ```````````````````````12 13 - Various Pocoo Members14 - Chris Adams15+- Flavio Percoco Premoli16+- Dj Gilcreaseadded:HACKING+15 added
1+Where possible, please follow PEP8 with regard to coding style. Sometimes the2+line length restriction is too hard to follow, so don't bend over backwards3+there.4+5+Triple-quotes should always be """, single quotes are ' unless using " would6+result in less escaping within the string.7+8+All modules, functions, and methods should be well documented reStructuredText9+for Sphinx AutoDoc.10+11+All functionality should be available in pure Python. Optional C (via Cython)12+implementations may be written for performance reasons, but should never13+replace the Python implementation.14+15+Lastly, don't take yourself too seriously :)modified:HISTORY.rst+12 added
1 History2 -------3 4+0.3.0 (2011-02-25)5+++++++++++++++++++6+7+* Automatic Authentication API Change8+* Smarter Query URL Parameterization9+* Allow file uploads and POST data together10+* New Authentication Manager System11+ - Simpler Basic HTTP System12+ - Supports all build-in urllib2 Auths13+ - Allows for custom Auth Handlers14+15+16 0.2.4 (2011-02-19)17 ++++++++++++++++++18 19 * Python 2.5 Support41 unmodified linesmodified:README.rst+33 added-30 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- 19-- Simple Basic HTTP Authentication18+19+- Simple Authentication20 + Simple URL + HTTP Auth Registry21 22 23 Usage5 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- 41- >>> conv_auth = requests.AuthObject('requeststest', 'requeststest')40+41+ >>> conv_auth = ('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- 88- Response.status_code:87+88+ Response.status_code89 (Integer) Received HTTP Status Code Response90 91- Response.headers:91+ Response.headers92 (Dictionary) Received HTTP Response Headers93 94- Response.content:94+ Response.content95 (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.cached104+ (Bool) True if Response.content is stored within the object.105+106 Response.error107 (HTTPError) If an HTTPError occurred (e.g. status of 404), Otherwise this is None.105- 108+109 Response.raise_for_status()110 Raises HTTPError if a request is not kosher.111 112 113 **HTTP Authentication Registry:**114 115 You can register AuthObjects to automatically enable HTTP Authentication on requests that contain a registered base URL string.116 114- >>> requests.add_autoauth(url, authobject)117+ >>> requests.auth_manager.add_auth(url, authobject)118 119 120 121 Installation1 unmodified line123 124 To install requests, simply: ::125 126 $ pip install requests124- 127+128 Or, if you absolutely must: ::129 130 $ easy_install requests131 132 But, you really shouldn't do that.130- 133 134 135+136 Contribute137 ----------138 139 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+33 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 30+ def test_HTTP_200_OK_GET_WITH_PARAMS(self):31 32+ heads = {'User-agent': 'Mozilla/5.0'}33+ 34+ r = requests.get('http://www.google.com/search', params={'q': 'test'}, headers=heads)35+ self.assertEqual(r.status_code, 200)36+37+38+ def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):39+40+ heads = {'User-agent': 'Mozilla/5.0'}41+42+ r = requests.get('http://google.com/search?test=true', params={'q': 'test'}, headers=heads)43+ self.assertEqual(r.status_code, 200)44+ 45 def test_HTTP_200_OK_HEAD(self):46 r = requests.head('http://google.com')47 self.assertEqual(r.status_code, 200)48 37-49 def test_HTTPS_200_OK_HEAD(self):50 r = requests.head('https://google.com')51 self.assertEqual(r.status_code, 200)52 42-53 def test_AUTH_HTTPS_200_OK_GET(self):44- auth = requests.AuthObject('requeststest', 'requeststest')54+ auth = ('requeststest', 'requeststest')55 url = 'https://convore.com/api/account/verify.json'56 r = requests.get(url, auth=auth)57 58 self.assertEqual(r.status_code, 200)59 50-51- requests.add_autoauth(url, auth)52-60 r = requests.get(url)61 self.assertEqual(r.status_code, 200)62 63 # reset auto authentication57- requests.AUTOAUTHS = []64+ requests.auth_manager.empty()65 59-60-66 def test_POSTBIN_GET_POST_FILES(self):67 68 bin = requests.post('http://www.postbin.org/')69+ print bin.url70 self.assertEqual(bin.status_code, 200)65-71+ 72 post = requests.post(bin.url, data={'some': 'data'})73 self.assertEqual(post.status_code, 201)74 75 post2 = requests.post(bin.url, files={'some': open('test_requests.py')})76 self.assertEqual(post2.status_code, 201)77 78+ def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):79 80+ bin = requests.post('http://www.postbin.org/')81+ 82+ self.assertEqual(bin.status_code, 200)83+84+ post2 = requests.post(bin.url, files={'some': open('test_requests.py')}, data={'some': 'data'})85+ self.assertEqual(post2.status_code, 201)86+87 def test_nonzero_evaluation(self):88 r = requests.get('http://google.com/some-404-url')89 self.assertEqual(bool(r), False)90 91 r = requests.get('http://google.com/')92 self.assertEqual(bool(r), True)79-80-93+ 94 def test_request_ok_set(self):95 r = requests.get('http://google.com/some-404-url')96 self.assertEqual(r.ok, False)84-85-97+ 98 def test_status_raising(self):99 r = requests.get('http://google.com/some-404-url')100 self.assertRaises(requests.HTTPError, r.raise_for_status)89-101+ 102 r = requests.get('http://google.com/')103 self.assertFalse(r.error)104 r.raise_for_status()105+ 106 107 108+109 if __name__ == '__main__':110 unittest.main()