Merge branch 'release/0.5.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 add6fea, e2d6a92 · Browse files · 15 files·+432 added−184 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+432 added−184 removed
- other:+432 added−184 removed
Provenance
- Commit
2d98ca7- Tree
f411805- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
add6fea- Parent 2
e2d6a92
15 files changed+432 added−184 removed
modified:docs/_themes/kr/layout.html+14 added
28 unmodified lines2930313233343536373839404142434445464728 unmodified lines var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
</script>
<script type="text/javascript"> (function() { var t = document.createElement('script'); t.type = 'text/javascript'; t.async = true; t.id = 'gauges-tracker'; t.setAttribute('data-site-id', '4ddc27f6613f5d186d000007'); t.src = '//secure.gaug.es/track.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(t, s); })(); </script>{%- endblock %}modified:docs/api.rst+3 added-1 removed
14 unmodified lines15 16 All of Request's functionality can be accessed by these 5 methods. They17 all return a :class:`Response <models.Response>` object.18 19+.. autofunction:: head20 .. autofunction:: get21 .. autofunction:: post22 .. autofunction:: put23+.. autofunction:: patch24 .. autofunction:: delete23-.. autofunction:: head25 26+27 -----------28 29 30 .. autoclass:: requests.models.Response38 unmodified linesmodified:docs/index.rst+3 added-3 removed
25 unmodified lines26 'application/json'27 28 See `the same code, without Requests <https://gist.github.com/973705>`_.29 30-Requests allow you to send **GET**, **HEAD**, **PUT**,31-**POST**, and **DELETE** HTTP requests. You can add headers, form data,30+Requests allow you to send **HEAD**, **GET**, **POST**, **PUT**,31+**PATCH**, and **DELETE** HTTP requests. You can add headers, form data,32 multipart files, and parameters with simple Python dictionaries, and access the33 response data in the same way. It's powered by :py:class:`urllib2`, but it does34 all the hard work and crazy hacks for you.35 36 Testimonals37 -----------38 39-`Twitter, Inc <http://twitter.com>`_ and `The Library of Congress <http://www.loc.gov/>`_ use Requests internally.39+`Twitter, Inc <http://twitter.com>`_ uses Requests internally.40 41 **Daniel Greenfeld**42 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to @kennethreitz's request library. Today has been AWESOME.43 46 unmodified linesmodified:requests/api.py+91 added-28 removed
9 unmodified lines10 :license: ISC, see LICENSE for more details.11 12 """13 14-import requests14 import config15 from .models import Request, Response, AuthManager, AuthObject, auth_manager16 17 19-__all__ = ('request', 'get', 'head', 'post', 'put', 'delete')18+__all__ = ('request', 'get', 'head', 'post', 'patch', 'put', 'delete')19 20+def request(method, url,21+ params=None, data=None, headers=None, cookies=None, files=None, auth=None,22+ timeout=None, allow_redirects=False, proxies=None):23 22-23-def request(method, url, **kwargs):24 """Constructs and sends a :class:`Request <models.Request>`. Returns :class:`Response <models.Response>` object.25 26 :param method: method for the new :class:`Request` object.27 :param url: URL for the new :class:`Request` object.28- :param params: (optional) Dictionary of GET/HEAD/DELETE Parameters to send with the :class:`Request`.29- :param data: (optional) Bytes/Dictionary of PUT/POST Data to send with the :class:`Request`.28+ :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.29+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.30 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.31 :param cookies: (optional) CookieJar object to send with the :class:`Request`.32 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.33 :param auth: (optional) AuthObject to enable Basic HTTP Auth.34 :param timeout: (optional) Float describing the timeout of the request.35 :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.36+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.37 """37- data = kwargs.pop('data', dict()) or kwargs.pop('params', dict())38 39- r = Request(method=method, url=url, data=data, headers=kwargs.pop('headers', dict()),40- cookiejar=kwargs.get('cookies', None),41- files=kwargs.get('files', None),42- auth=kwargs.get('auth', auth_manager.get_auth(url)),43- timeout=kwargs.get('timeout', config.settings.timeout),44- allow_redirects=kwargs.get('allow_redirects', None)39+ r = Request(40+ method = method,41+ url = url,42+ data = data,43+ params = params,44+ headers = headers,45+ cookiejar = cookies,46+ files = files,47+ auth = auth or auth_manager.get_auth(url),48+ timeout = timeout or config.settings.timeout,49+ allow_redirects = allow_redirects,50+ proxies = proxies51 )52 53 r.send()54 55 return r.response56 57 52-def get(url, params={}, headers={}, cookies=None, auth=None, **kwargs):58+def get(url,59+ params=None, headers=None, cookies=None, auth=None, timeout=None,60+ proxies=None):61+62 """Sends a GET request. Returns :class:`Response` object.63 64 :param url: URL for the new :class:`Request` object.56- :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.65+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.66 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.67 :param cookies: (optional) CookieJar object to send with the :class:`Request`.68 :param auth: (optional) AuthObject to enable Basic HTTP Auth.69 :param timeout: (optional) Float describing the timeout of the request.70+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.71 """72 63- return request('GET', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)73+ return request('GET', url,74+ params=params, headers=headers, cookies=cookies, auth=auth,75+ timeout=timeout, proxies=proxies)76 77 66-def head(url, params={}, headers={}, cookies=None, auth=None, **kwargs):78+def head(url,79+ params=None, headers=None, cookies=None, auth=None, timeout=None,80+ proxies=None):81+82 """Sends a HEAD request. Returns :class:`Response` object.83 84 :param url: URL for the new :class:`Request` object.70- :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.85+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.86 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.87 :param cookies: (optional) CookieJar object to send with the :class:`Request`.88 :param auth: (optional) AuthObject to enable Basic HTTP Auth.89 :param timeout: (optional) Float describing the timeout of the request.90+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.91 """92 77- return request('HEAD', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)93+ return request('HEAD', url,94+ params=params, headers=headers, cookies=cookies, auth=auth,95+ timeout=timeout, proxies=proxies)96 97 80-def post(url, data={}, headers={}, files=None, cookies=None, auth=None, **kwargs):98+def post(url,99+ data='', headers=None, files=None, cookies=None, auth=None, timeout=None,100+ allow_redirects=False, params=None, proxies=None):101+102 """Sends a POST request. Returns :class:`Response` object.103 104 :param url: URL for the new :class:`Request` object.84- :param data: (optional) Dictionary of POST data to send with the :class:`Request`.105+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.106 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.107 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.108 :param cookies: (optional) CookieJar object to send with the :class:`Request`.109 :param auth: (optional) AuthObject to enable Basic HTTP Auth.110 :param timeout: (optional) Float describing the timeout of the request.111+ :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.112+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.113+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.114 """115 92- return request('POST', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)116+ return request('POST', url,117+ params=params, data=data, headers=headers, files=files,118+ cookies=cookies, auth=auth, timeout=timeout,119+ allow_redirects=allow_redirects, proxies=proxies)120 121 95-def put(url, data='', headers={}, files={}, cookies=None, auth=None, **kwargs):122+def put(url, data='', headers=None, files=None, cookies=None, auth=None,123+ timeout=None, allow_redirects=False, params=None, proxies=None):124 """Sends a PUT request. Returns :class:`Response` object.125 126 :param url: URL for the new :class:`Request` object.99- :param params: (optional) Bytes of PUT Data to send with the :class:`Request`.127+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.128 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.129 :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.130 :param cookies: (optional) CookieJar object to send with the :class:`Request`.131 :param auth: (optional) AuthObject to enable Basic HTTP Auth.132 :param timeout: (optional) Float describing the timeout of the request.133+ :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.134+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.135+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.136 """137 107- return request('PUT', url, data=data, headers=headers, files=files, cookies=cookies, auth=auth, **kwargs)138+ return request('PUT', url,139+ params=params, data=data, headers=headers, files=files,140+ cookies=cookies, auth=auth, timeout=timeout,141+ allow_redirects=allow_redirects, proxies=proxies)142 143 110-def delete(url, params={}, headers={}, cookies=None, auth=None, **kwargs):144+def patch(url, data='', headers=None, files=None, cookies=None, auth=None,145+ timeout=None, allow_redirects=False, params=None, proxies=None):146+ """Sends a PATCH request. Returns :class:`Response` object.147+148+ :param url: URL for the new :class:`Request` object.149+ :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.150+ :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.151+ :param files: (optional) Dictionary of 'filename': file-like-objects for multipart encoding upload.152+ :param cookies: (optional) CookieJar object to send with the :class:`Request`.153+ :param auth: (optional) AuthObject to enable Basic HTTP Auth.154+ :param timeout: (optional) Float describing the timeout of the request.155+ :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.156+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.157+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.158+ """159+160+ return request('PATCH', url,161+ params=params, data=data, headers=headers, files=files,162+ cookies=cookies, auth=auth, timeout=timeout,163+ allow_redirects=allow_redirects, proxies=proxies)164+165+166+def delete(url,167+ params=None, headers=None, cookies=None, auth=None, timeout=None,168+ allow_redirects=False, proxies=None):169+170 """Sends a DELETE request. Returns :class:`Response` object.171 172 :param url: URL for the new :class:`Request` object.114- :param params: (optional) Dictionary of DELETE Parameters to send with the :class:`Request`.173+ :param params: (optional) Dictionary of parameters, or bytes, to be sent in the query string for the :class:`Request`.174 :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.175 :param cookies: (optional) CookieJar object to send with the :class:`Request`.176 :param auth: (optional) AuthObject to enable Basic HTTP Auth.177 :param timeout: (optional) Float describing the timeout of the request.178+ :param allow_redirects: (optional) Boolean. Set to True if redirect following is allowed.179+ :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.180 """181 121- return request('DELETE', url, params=params, headers=headers, cookies=cookies, auth=auth, **kwargs)182+ return request('DELETE', url,183+ params=params, headers=headers, cookies=cookies, auth=auth,184+ timeout=timeout, allow_redirects=allow_redirects, proxies=proxies)modified:requests/config.py+1 added-1 removed
10 unmodified lines11 class Settings(object):12 _singleton = {}13 14 # attributes with defaults15- __attrs__ = ('timeout',)15+ __attrs__ = ('timeout', 'verbose')16 17 def __init__(self, **kwargs):18 super(Settings, self).__init__()19 37 unmodified linesmodified:requests/core.py+2 added-2 removed
10 unmodified lines11 12 """13 14 __title__ = 'requests'15-__version__ = '0.4.1'16-__build__ = 0x00040115+__version__ = '0.5.0'16+__build__ = 0x00050017 __author__ = 'Kenneth Reitz'18 __license__ = 'ISC'19 __copyright__ = 'Copyright 2011 Kenneth Reitz'20 5 unmodified linesmodified:requests/models.py+76 added-31 removed
4 unmodified lines5 ~~~~~~~~~~~~~~~6 7 """8 9-import requests9 import urllib10 import urllib211 import socket12 import zlib13 14 from urllib2 import HTTPError15 from urlparse import urlparse16+from datetime import datetime17 18+from .config import settings19 from .monkeys import Request as _Request, HTTPBasicAuthHandler, HTTPDigestAuthHandler, HTTPRedirectHandler20 from .structures import CaseInsensitiveDict21 from .packages.poster.encode import multipart_encode22 from .packages.poster.streaminghttp import register_openers, get_handlers23 from .exceptions import RequestException, AuthenticationError, Timeout, URLRequired, InvalidMethod24 25 26+REDIRECT_STATI = (301, 302, 303, 307)27 28+29 class Request(object):30 """The :class:`Request <models.Request>` object. It carries out all functionality of31 Requests. Recommended interface is with the Requests functions.32 """33 31- _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE')34+ _METHODS = ('GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH')35 33- def __init__(self, url=None, headers=dict(), files=None, method=None,34- data=dict(), auth=None, cookiejar=None, timeout=None,35- redirect=True, allow_redirects=False):36+ def __init__(self,37+ url=None, headers=dict(), files=None, method=None, data=dict(),38+ params=dict(), auth=None, cookiejar=None, timeout=None, redirect=False,39+ allow_redirects=False, proxies=None):40 41 socket.setdefaulttimeout(timeout)42 43 #: Request URL.3 unmodified lines47 #: Dictionary of files to multipart upload (``{filename: content}``).48 self.files = files49 #: HTTP Method to use. Available: GET, HEAD, PUT, POST, DELETE.50 self.method = method51+ #: Dictionary or byte of request body data to attach to the47- #: Form or Byte data to attach to the :class:`Request <models.Request>`.48- self.data = dict()52+ #: :class:`Request <models.Request>`.53+ self.data = None54+ #: Dictionary or byte of querystring data to attach to the55+ #: :class:`Request <models.Request>`.56+ self.params = None57 #: True if :class:`Request <models.Request>` is part of a redirect chain (disables history58 #: and HTTPError storage).59 self.redirect = redirect60 #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)61 self.allow_redirects = allow_redirects62+ # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})63+ self.proxies = proxies64 55- if hasattr(data, 'items'):56- for (k, v) in data.items():57- self.data.update({58- k.encode('utf-8') if isinstance(k, unicode) else k:59- v.encode('utf-8') if isinstance(v, unicode) else v60- })61- self._enc_data = urllib.urlencode(self.data)62- else:63- self._enc_data = self.data = data65+ self.data, self._enc_data = self._encode_params(data)66+ self.params, self._enc_params = self._encode_params(params)67 68 #: :class:`Response <models.Response>` instance, containing69 #: content and metadata of HTTP Response, once :attr:`sent <send>`.70 self.response = Response()44 unmodified lines115 auth_manager.add_auth(self.url, self.auth)116 117 _handlers.append(self.auth.handler)118 119+ if self.proxies:120+ _handlers.append(urllib2.ProxyHandler(self.proxies))121 122 _handlers.append(HTTPRedirectHandler)123 124 if not _handlers:14 unmodified lines139 opener.addheaders.remove((key, val))140 141 return opener.open142 143+144 def _build_response(self, resp):145 """Build internal :class:`Response <models.Response>` object from given response."""146 147 def build(resp):12 unmodified lines160 response.content = zlib.decompress(response.content, 16+zlib.MAX_WBITS)161 except zlib.error:162 pass163 164+ # TODO: Support deflate165+166 response.url = getattr(resp, 'url', None)167 168 return response169 1 unmodified line171 history = []172 173 r = build(resp)174 175+ if r.status_code in REDIRECT_STATI:176+ self.redirect = True177+178 if self.redirect:179 180 while (181 ('location' in r.headers) and5 unmodified lines187 history.append(r)188 189 url = r.headers['location']190 180- # Facilitate for non-RFC2616-compliant 'location' headers191+ # Facilitate non-RFC2616-compliant 'location' headers192 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')193 if not urlparse(url).netloc:194 parent_url_components = urlparse(self.url)195 url = '%s://%s/%s' % (parent_url_components.scheme, parent_url_components.netloc, url)5 unmodified lines201 method = self.method202 203 request = Request(204 url, self.headers, self.files, method,194- self.data, self.auth, self.cookiejar, redirect=False205+ self.data, self.params, self.auth, self.cookiejar,206+ redirect=True207 )208 request.send()209 r = request.response210 2 unmodified lines213 self.response = r214 215 216 @staticmethod205- def _build_url(url, data=None):206- """Build URLs."""217+ def _encode_params(data):218+ """Encode parameters in a piece of data.219 208- if urlparse(url).query:209- return '%s&%s' % (url, data)220+ If the data supplied is a dictionary, encodes each parameter in it, and221+ returns the dictionary of encoded parameters, and a urlencoded version222+ of that.223+224+ Otherwise, assumes the data is already encoded appropriately, and225+ returns it twice.226+227+ """228+ if hasattr(data, 'items'):229+ result = {}230+ for (k, v) in data.items():231+ result[k.encode('utf-8') if isinstance(k, unicode) else k] \232+ = v.encode('utf-8') if isinstance(v, unicode) else v233+ return result, urllib.urlencode(result)234 else:211- if data:212- return '%s?%s' % (url, data)235+ return data, data236+237+238+ def _build_url(self):239+ """Build the actual URL to use"""240+241+ if self._enc_params:242+ if urlparse(self.url).query:243+ return '%s&%s' % (self.url, self._enc_params)244 else:214- return url245+ return '%s?%s' % (self.url, self._enc_params)246+ else:247+ return self.url248 249 250 def send(self, anyway=False):251 """Sends the request. Returns True of successful, false if not.7 unmodified lines259 """260 self._checks()261 success = False262 263+ # Logging264+ if settings.verbose:265+ settings.verbose.write('%s %s %s\n' % (266+ datetime.now().isoformat(), self.method, self.url267+ ))268+269+270+ url = self._build_url()271 if self.method in ('GET', 'HEAD', 'DELETE'):231- req = _Request(self._build_url(self.url, self._enc_data), method=self.method)272+ req = _Request(url, method=self.method)273 else:274 275 if self.files:276 register_openers()1 unmodified line278 if self.data:279 self.files.update(self.data)280 281 datagen, headers = multipart_encode(self.files)241- req = _Request(self.url, data=datagen, headers=headers, method=self.method)282+ req = _Request(url, data=datagen, headers=headers, method=self.method)283 284 else:244- req = _Request(self.url, data=self._enc_data, method=self.method)285+ req = _Request(url, data=self._enc_data, method=self.method)286 287 if self.headers:288 req.headers.update(self.headers)289 5 unmodified lines295 296 if self.cookiejar is not None:297 self.cookiejar.extract_cookies(resp, req)298 258- except urllib2.HTTPError, why:299+ except (urllib2.HTTPError, urllib2.URLError), why:300+ if hasattr(why, 'reason'):301+ if isinstance(why.reason, socket.timeout):302+ why = Timeout(why)303+304 self._build_response(why)305 if not self.redirect:306 self.response.error = why262- except urllib2.URLError, error:263- raise Timeout if isinstance(error.reason, socket.timeout) else error307+308 else:309 self._build_response(resp)310 self.response.ok = True311 2 unmodified lines314 self.response.cached = True315 316 self.sent = self.response.ok317 318+319 return self.sent320 321 322 def read(self, *args):226 unmodified linesmodified:requests/monkeys.py-1 removed
24 unmodified lines25 return self.method26 27 return urllib2.Request.get_method(self)28 29-29 class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):30 31 def http_error_301(self, req, fp, code, msg, headers):32 pass58 unmodified linesmodified:requests/structures.py+4 added-40 removed
6 unmodified lines7 Datastructures that power Requests.8 9 """10 11-from UserDict import DictMixin12-13-14-class CaseInsensitiveDict(DictMixin):11+class CaseInsensitiveDict(dict):12 """Case-insensitive Dictionary for :class:`Response <models.Response>` Headers.13 14 For example, ``headers['content-encoding']`` will return the15 value of a ``'Content-Encoding'`` response header."""16 20- def __init__(self, *args, **kwargs):21- # super(CaseInsensitiveDict, self).__init__()22- self.data = dict(*args, **kwargs)23-24- def __repr__(self):25- return self.data.__repr__()26-27- def __getstate__(self):28- return self.data.copy()29-30- def __setstate__(self, d):31- self.data = d32-17 def _lower_keys(self):34- return map(str.lower, self.data.keys())18+ return map(str.lower, self.keys())19 20 21 def __contains__(self, key):22 return key.lower() in self._lower_keys()23 24 25 def __getitem__(self, key):42-43- if key.lower() in self:26+ # We allow fall-through here, so values default to None27+ if key in self:28 return self.items()[self._lower_keys().index(key.lower())][1]45-46-47- def __setitem__(self, key, value):48- return self.data.__setitem__(key, value)49-50-51- def __delitem__(self, key):52- return self.data.__delitem__(key)53-54-55- def __keys__(self):56- return self.data.__keys__()57-58-59- def __iter__(self):60- return self.data.__iter__()61-62-63- def iteritems(self):64- return self.data.iteritems()modified:AUTHORS+8 added-1 removed
16 unmodified lines17 - Justin Murphy18 - Rob Madole19 - Aram Dulyan20 - Johannes Gorset21-- 村山めがね (Megane Murayama)21+- 村山めがね (Megane Murayama)22+- James Rowe23+- Daniel Schauenberg24+- Zbigniew Siciarz25+- Daniele Tricoli 'Eriol'26+- Richard Boulton27+- Miguel Olivares <miguel@moliware.com>28+- Alberto Paromodified:HISTORY.rst+13 added
1 History2 -------3 4+0.5.0 (2011-06-21)5+++++++++++++++++++6+7+* PATCH Support8+* Support for Proxies9+* HTTPBin Test Suite10+* Redirect Fixes11+* settings.verbose stream writing12+* Querystrings for all methods13+* URLErrors (Connection Refused, Timeout, Invalid URLs) are treated as explicity raised14+ ``r.requests.get('hwe://blah'); r.raise_for_status()``15+16+17 0.4.1 (2011-05-22)18 ++++++++++++++++++19 20 * Improved Redirection Handling101 unmodified linesmodified:README.rst+18 added-14 removed
1-Requests: The Simple (e.g. usable) HTTP Module2-==============================================1+Requests: HTTP for Humans2+=========================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).5 6 But this one's different. This one's going to be awesome. And simple.2 unmodified lines9 10 Features11 --------12 13-- Extremely simple GET, HEAD, POST, PUT, DELETE Requests13+- Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests14 + Simple HTTP Header Request Attachment15 + Simple Data/Params Request Attachment16 + Simple Multipart File Uploads17 + CookieJar Support18 + Redirection History19+ + Proxy Support20 + Redirection Recursion Urllib Fix21 + Auto Decompression of GZipped Content22 + Unicode URL Support23 11 unmodified lines35 36 37 HTTPS? Basic Authentication? ::38 38- >>> r = requests.get('https://convore.com/api/account/verify.json')39+ >>> r = requests.get('https://httpbin.ep.ip/basic-auth/user/pass')40 >>> r.status_code41 40142 43 44 Uh oh, we're not authorized! Let's add authentication. ::45 45- >>> conv_auth = ('requeststest', 'requeststest')46- >>> r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)46+ >>> r = requests.get(https://httpbin.ep.ip/basic-auth/user/pass', auth=('user', 'pass'))47 48 >>> r.status_code49 20050 51 >>> r.headers['content-type']52 'application/json'53 54 >>> r.content55- '{"username": "requeststest", "url": "/users/requeststest/", "id": "9408", "img": "censored-long-url"}'55+ '{"authenticated": true, "user": "user"}'56 57 58 59 API5 unmodified lines65 66 If a {filename: fileobject} dictionary is passed in (files=...), a multipart_encode upload will be performed.67 If CookieJar object is is passed in (cookies=...), the cookies will be sent with the request.68 69+ HEAD Requests70+ >>> requests.head(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})71+ <Response [200]>72+73 GET Requests70- >>> requests.get(url, params={}, headers={}, cookies=None, auth=None)74+ >>> requests.get(url, params={}, headers={}, cookies=None, auth=None, timeout=None, proxies={})75 <Response [200]>76 73- HEAD Requests74- >>> requests.head(url, params={}, headers={}, cookies=None, auth=None)77+ POST Requests78+ >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})79 <Response [200]>80 81 PUT Requests78- >>> requests.put(url, data='', headers={}, files={}, cookies=None, auth=None)82+ >>> requests.put(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})83 <Response [200]>84 81- POST Requests82- >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None)85+ PATCH Requests86+ >>> requests.post(url, data={}, headers={}, files={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})87 <Response [200]>88 89 DELETE Requests86- >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None)90+ >>> requests.delete(url, params={}, headers={}, cookies=None, auth=None, timeout=None, allow_redirects=False, params{}, proxies={})91 <Response [200]>92 93 94 **Responses:**66 unmodified linesmodified:setup.py+4 added-1 removed
3 unmodified lines4 import os5 import sys6 import requests7 8+try:9+ from setuptools import setup10+except ImportError:8-from distutils.core import setup11+ from distutils.core import setup12 13 14 15 if sys.argv[-1] == "publish":41 unmodified linesmodified:test_requests.py+193 added-56 removed
4 unmodified lines5 6 import unittest7 import cookielib8 9+import omnijson as json10+11 import requests12 13 14+15+HTTPBIN_URL = 'http://httpbin.org/'16+HTTPSBIN_URL = 'https://httpbin.ep.io/'17+18+# HTTPBIN_URL = 'http://staging.httpbin.org/'19+# HTTPSBIN_URL = 'https://httpbin-staging.ep.io/'20+21+22+def httpbin(*suffix):23+ """Returns url for HTTPBIN resource."""24+25+ return HTTPBIN_URL + '/'.join(suffix)26+27+28+def httpsbin(*suffix):29+ """Returns url for HTTPSBIN resource."""30+31+ return HTTPSBIN_URL + '/'.join(suffix)32+33+34+35 class RequestsTestSuite(unittest.TestCase):36 """Requests test cases."""37 38+39 def setUp(self):40 pass41 42+43 def tearDown(self):44 """Teardown."""45 pass46 47+48 def test_invalid_url(self):49 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')50 51+52 def test_HTTP_200_OK_GET(self):26- r = requests.get('http://google.com')53+ r = requests.get(httpbin('/'))54 self.assertEqual(r.status_code, 200)55 56+57 def test_HTTPS_200_OK_GET(self):30- r = requests.get('https://google.com')58+ r = requests.get(httpsbin('/'))59 self.assertEqual(r.status_code, 200)60 61+62 def test_HTTP_200_OK_GET_WITH_PARAMS(self):63 heads = {'User-agent': 'Mozilla/5.0'}64 36- r = requests.get('http://www.google.com/search', params={'q': 'test'}, headers=heads)65+ r = requests.get(httpbin('user-agent'), headers=heads)66+67+ assert heads['User-agent'] in r.content68 self.assertEqual(r.status_code, 200)69 70+71 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):72 heads = {'User-agent': 'Mozilla/5.0'}73 42- r = requests.get('http://google.com/search?test=true', params={'q': 'test'}, headers=heads)74+ r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)75 self.assertEqual(r.status_code, 200)76 77+78 def test_user_agent_transfers(self):79 """Issue XX"""80+81 heads = {82 'User-agent':83 'Mozilla/5.0 (github.com/kennethreitz/requests)'84 }85 52- r = requests.get('http://whatsmyua.com', headers=heads);86+ r = requests.get(httpbin('user-agent'), headers=heads);87 self.assertTrue(heads['User-agent'] in r.content)88 89 heads = {90 'user-agent':91 'Mozilla/5.0 (github.com/kennethreitz/requests)'92 }93 60- r = requests.get('http://whatsmyua.com', headers=heads);94+ r = requests.get(httpbin('user-agent'), headers=heads);95 self.assertTrue(heads['user-agent'] in r.content)96 97+98 def test_HTTP_200_OK_HEAD(self):64- r = requests.head('http://google.com')99+ r = requests.head(httpbin('/'))100 self.assertEqual(r.status_code, 200)101 102+103 def test_HTTPS_200_OK_HEAD(self):68- r = requests.head('https://google.com')104+ r = requests.head(httpsbin('/'))105 self.assertEqual(r.status_code, 200)106 107+108+ def test_HTTP_200_OK_PUT(self):109+ r = requests.put(httpbin('put'))110+ self.assertEqual(r.status_code, 200)111+112+113+ def test_HTTPS_200_OK_PUT(self):114+ r = requests.put(httpsbin('put'))115+ self.assertEqual(r.status_code, 200)116+117+118+ def test_HTTP_200_OK_PATCH(self):119+ r = requests.patch(httpbin('patch'))120+ self.assertEqual(r.status_code, 200)121+122+123+ def test_HTTPS_200_OK_PATCH(self):124+ r = requests.patch(httpsbin('patch'))125+ self.assertEqual(r.status_code, 200)126+127+128 def test_AUTH_HTTPS_200_OK_GET(self):72- auth = ('requeststest', 'requeststest')73- url = 'https://convore.com/api/account/verify.json'129+ auth = ('user', 'pass')130+ url = httpsbin('basic-auth', 'user', 'pass')131 r = requests.get(url, auth=auth)132 133 self.assertEqual(r.status_code, 200)134 2 unmodified lines137 138 # reset auto authentication139 requests.auth_manager.empty()140 141+142 def test_POSTBIN_GET_POST_FILES(self):85- bin = requests.post('http://www.postbin.org/')86- self.assertEqual(bin.status_code, 302)143+ url = httpbin('post')144+ post = requests.post(url).raise_for_status()145 88- post_url = bin.headers['location']89- post = requests.post(post_url, data={'some': 'data'})90- self.assertEqual(post.status_code, 201)146+ post = requests.post(url, data={'some': 'data'})147+ self.assertEqual(post.status_code, 200)148 92- post2 = requests.post(post_url, files={'some': open('test_requests.py')})93- self.assertEqual(post2.status_code, 201)149+ post2 = requests.post(url, files={'some': open('test_requests.py')})150+ self.assertEqual(post2.status_code, 200)151 95- post3 = requests.post(post_url, data='[{"some": "json"}]')96- self.assertEqual(post.status_code, 201)152+ post3 = requests.post(url, data='[{"some": "json"}]')153+ self.assertEqual(post3.status_code, 200)154 155 156 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):100- bin = requests.post('http://www.postbin.org/')101- self.assertEqual(bin.status_code, 302)157 103- post_url = bin.headers['location']158+ url = httpbin('post')159+ post = requests.post(url, files={'some': open('test_requests.py')}, data={'some': 'data'})160+ self.assertEqual(post.status_code, 200)161 105- post2 = requests.post(post_url, files={'some': open('test_requests.py')}, data={'some': 'data'})106- self.assertEqual(post2.status_code, 201)162 108-163 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):110- bin = requests.post('http://www.postbin.org/')111- self.assertEqual(bin.status_code, 302)164 113- post_url = bin.headers['location']165+ url = httpbin('post')166 115- post2 = requests.post(post_url, files={'some': open('test_requests.py')},116- headers = {'User-Agent': 'requests-tests'})167+ post2 = requests.post(url, files={'some': open('test_requests.py')},168+ headers = {'User-Agent': 'requests-tests'})169 118- self.assertEqual(post2.status_code, 201)170+ self.assertEqual(post2.status_code, 200)171 172 173 def test_nonzero_evaluation(self):122- r = requests.get('http://google.com/some-404-url')174+ r = requests.get(httpbin('status', '500'))175 self.assertEqual(bool(r), False)176 125- r = requests.get('http://google.com/')177+ r = requests.get(httpbin('/'))178 self.assertEqual(bool(r), True)179 180+181 def test_request_ok_set(self):129- r = requests.get('http://google.com/some-404-url')182+ r = requests.get(httpbin('status', '404'))183 self.assertEqual(r.ok, False)184 185+186 def test_status_raising(self):133- r = requests.get('http://google.com/some-404-url')187+ r = requests.get(httpbin('status', '404'))188 self.assertRaises(requests.HTTPError, r.raise_for_status)189 136- r = requests.get('http://google.com/')190+ r = requests.get(httpbin('status', '200'))191 self.assertFalse(r.error)192 r.raise_for_status()193 194+195 def test_cookie_jar(self):141- """142- .. todo:: This really doesn't test to make sure the cookie is working143- """196 197 jar = cookielib.CookieJar()198 self.assertFalse(jar)199 148- requests.get('http://google.com', cookies=jar)200+ url = httpbin('cookies', 'set', 'requests_cookie', 'awesome')201+ r = requests.get(url, cookies=jar)202 self.assertTrue(jar)203 204+ cookie_found = False205+ for cookie in jar:206+ if cookie.name == 'requests_cookie':207+ self.assertEquals(cookie.value, 'awesome')208+ cookie_found = True209+ self.assertTrue(cookie_found)210+211+ r = requests.get(httpbin('cookies'), cookies=jar)212+ self.assertTrue('awesome' in r.content)213+214+215 def test_decompress_gzip(self):216 153- r = requests.get('http://api.stackoverflow.com/1.1/users/495995/top-answer-tags')217+ r = requests.get(httpbin('gzip'))218 r.content.decode('ascii')219 220+221 def test_autoauth(self):222 158- conv_auth = ('requeststest', 'requeststest')159- requests.auth_manager.add_auth('convore.com', conv_auth)223+ http_auth = ('user', 'pass')224+ requests.auth_manager.add_auth('httpbin.org', http_auth)225 161- r = requests.get('https://convore.com/api/account/verify.json')226+ r = requests.get(httpbin('basic-auth', 'user', 'pass'))227 self.assertEquals(r.status_code, 200)228 229+230 def test_unicode_get(self):165- requests.get('http://google.com', params={'foo': u'føø'})166- requests.get('http://google.com', params={u'føø': u'føø'})167- requests.get('http://google.com', params={'føø': 'føø'})168- requests.get('http://google.com', params={'foo': u'foo'})169- requests.get('http://google.com/ø', params={'foo': u'foo'})231 232+ url = httpbin('/')233+234+ requests.get(url, params={'foo': u'føø'})235+ requests.get(url, params={u'føø': u'føø'})236+ requests.get(url, params={'føø': 'føø'})237+ requests.get(url, params={'foo': u'foo'})238+ requests.get(httpbin('ø'), params={'foo': u'foo'})239+240+241 def test_httpauth_recursion(self):172- conv_auth = ('requeststest', 'bad_password')242+ http_auth = ('user', 'BADpass')243 174- r = requests.get('https://convore.com/api/account/verify.json', auth=conv_auth)244+ r = requests.get(httpbin('basic-auth', 'user', 'pass'), auth=http_auth)245 self.assertEquals(r.status_code, 401)246 247+248 def test_settings(self):178- with requests.settings(timeout=0.0001):179- self.assertRaises(requests.Timeout, requests.get, 'http://google.com')249 181- with requests.settings(timeout=10):182- requests.get('http://google.com')250+ def test():251+ r = requests.get(httpbin(''))252+ r.raise_for_status()253 254+ with requests.settings(timeout=0.0000001):255+ self.assertRaises(requests.Timeout, test)256+257+ with requests.settings(timeout=100):258+ requests.get(httpbin(''))259+260+261+ def test_urlencoded_post_data(self):262+ r = requests.post(httpbin('post'), data=dict(test='fooaowpeuf'))263+ self.assertEquals(r.status_code, 200)264+ self.assertEquals(r.headers['content-type'], 'application/json')265+ self.assertEquals(r.url, httpbin('post'))266+ rbody = json.loads(r.content)267+ self.assertEquals(rbody.get('form'), dict(test='fooaowpeuf'))268+ self.assertEquals(rbody.get('data'), '')269+270+271 def test_nonurlencoded_post_data(self):185- requests.post('http://google.com', data='foo')272+ r = requests.post(httpbin('post'), data='fooaowpeuf')273+ self.assertEquals(r.status_code, 200)274+ self.assertEquals(r.headers['content-type'], 'application/json')275+ self.assertEquals(r.url, httpbin('post'))276+ rbody = json.loads(r.content)277+ # Body wasn't valid url encoded data, so the server returns None as278+ # "form" and the raw body as "data".279+ self.assertEquals(rbody.get('form'), None)280+ self.assertEquals(rbody.get('data'), 'fooaowpeuf')281 282 283+ def test_urlencoded_post_querystring(self):284+ r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'))285+ self.assertEquals(r.status_code, 200)286+ self.assertEquals(r.headers['content-type'], 'application/json')287+ self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))288+ rbody = json.loads(r.content)289+ self.assertEquals(rbody.get('form'), {}) # No form supplied290+ self.assertEquals(rbody.get('data'), '')291 292+293+ def test_nonurlencoded_post_querystring(self):294+ r = requests.post(httpbin('post'), params='fooaowpeuf')295+ self.assertEquals(r.status_code, 200)296+ self.assertEquals(r.headers['content-type'], 'application/json')297+ self.assertEquals(r.url, httpbin('post?fooaowpeuf'))298+ rbody = json.loads(r.content)299+ self.assertEquals(rbody.get('form'), {}) # No form supplied300+ self.assertEquals(rbody.get('data'), '')301+302+303+ def test_urlencoded_post_query_and_data(self):304+ r = requests.post(httpbin('post'), params=dict(test='fooaowpeuf'),305+ data=dict(test2="foobar"))306+ self.assertEquals(r.status_code, 200)307+ self.assertEquals(r.headers['content-type'], 'application/json')308+ self.assertEquals(r.url, httpbin('post?test=fooaowpeuf'))309+ rbody = json.loads(r.content)310+ self.assertEquals(rbody.get('form'), dict(test2='foobar'))311+ self.assertEquals(rbody.get('data'), '')312+313+314+ def test_nonurlencoded_post_query_and_data(self):315+ r = requests.post(httpbin('post'), params='fooaowpeuf',316+ data="foobar")317+ self.assertEquals(r.status_code, 200)318+ self.assertEquals(r.headers['content-type'], 'application/json')319+ self.assertEquals(r.url, httpbin('post?fooaowpeuf'))320+ rbody = json.loads(r.content)321+ self.assertEquals(rbody.get('form'), None)322+ self.assertEquals(rbody.get('data'), 'foobar')323+324+325+326 if __name__ == '__main__':327 unittest.main()modified:tox.ini+2 added-5 removed
1 [tox]2-envlist = py25,py26,py27,pypy2+envlist = py25,py26,py273 4 [testenv]5 commands=py.test --junitxml=junit-{envname}.xml6 deps =7 pytest8-9-[testenv:pypy]10-basepython=/usr/bin/pypy11-8+ omnijson