Merge branch 'develop' of github.com:kennethreitz/requests into develop
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 6e26f57, eab2ab9 · Browse files · 14 files·+104 added−63 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+104 added−63 removed
- tests:+6 added−0 removed
- other:+98 added−63 removed
Provenance
- Commit
4c1852f- Tree
027c2be- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
6e26f57- Parent 2
eab2ab9
14 files changed+104 added−63 removed
modified:docs/community/out-there.rst-3 removed
48 unmodified lines49 Requests is available installed as a Debian package! Debian Etch Ubuntu, since Oneiric::50 51 $ apt-get install python-requests52 53-Unfortunately, the most recent version available is v0.5.0. If you're on the54-Debian Python Package team, I'd love an update of that :)53 56-54 Fedora and RedHat55 -----------------56 57 You can easily install Requests v0.6.1 with yum on rpm-based systems::6 unmodified linesmodified:docs/user/quickstart.rst+26 added
28 unmodified lines29 30 Now, we have a :class:`Response` object called ``r``. We can get all the31 information we need from this.32 33+Typically, you want to send some sort of data in the urls query string.34+To do this, simply pass a dictionary to the `params` argument. Your35+dictionary of data will automatically be encoded when the request is made::36 37+ >>> payload = {'key1': 'value1', 'key2': 'value2'}38+ >>> r = requests.get("http://httpbin.org/get", params=payload)39+ >>> print r.text40+ {41+ "origin": "179.13.100.4",42+ "args": {43+ "key2": "value2",44+ "key1": "value1"45+ },46+ "url": "http://httpbin.org/get",47+ "headers": {48+ "Connections": "keep-alive",49+ "Content-Length": "",50+ "Accept-Encoding": "identity, deflate, compress, gzip",51+ "Accept": "*/*",52+ "User-Agent": "python-requests/0.11.0",53+ "Host": httpbin.org",54+ "Content-Type": ""55+ },56+ }57+58+59+60 Response Content61 ----------------62 63 We can read the content of the server's response::369 unmodified linesmodified:requests/packages/oreos/monkeys.py+1 added-1 removed
253 unmodified lines254 # _Translator hash-table for fast quoting255 #256 _RFC2965Forbidden = "[]:{}="257 _LegalChars = ( string.ascii_letters + string.digits + 258- "!#$%&'*+-.^_`|~_" + _RFC2965Forbidden )258+ "!#$%&'*+-.^_`|~_@" + _RFC2965Forbidden )259 _Translator = {260 '\000' : '\\000', '\001' : '\\001', '\002' : '\\002',261 '\003' : '\\003', '\004' : '\\004', '\005' : '\\005',262 '\006' : '\\006', '\007' : '\\007', '\010' : '\\010',511 unmodified linesmodified:requests/__init__.py+2 added-2 removed
13 unmodified lines14 15 """16 17 __title__ = 'requests'18-__version__ = '0.10.8'19-__build__ = 0x00100818+__version__ = '0.11.0'19+__build__ = 0x00110020 __author__ = 'Kenneth Reitz'21 __license__ = 'ISC'22 __copyright__ = 'Copyright 2012 Kenneth Reitz'23 10 unmodified linesmodified:requests/api.py+8 added-7 removed
31 unmodified lines32 :param session: (optional) A :class:`Session` object to be used for the request.33 :param config: (optional) A configuration dictionary.34 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.35 :param prefetch: (optional) if ``True``, the response content will be immediately downloaded.36+ :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.37 """38 39 s = kwargs.pop('session') if 'session' in kwargs else sessions.session()40 return s.request(method=method, url=url, **kwargs)3 unmodified lines44 def get(url, **kwargs):45 """Sends a GET request. Returns :class:`Response` object.46 47 :param url: URL for the new :class:`Request` object.47- :param **kwargs: Optional arguments that ``request`` takes.48+ :param \*\*kwargs: Optional arguments that ``request`` takes.49 """50 51 kwargs.setdefault('allow_redirects', True)52 return request('get', url, **kwargs)2 unmodified lines55 def options(url, **kwargs):56 """Sends a OPTIONS request. Returns :class:`Response` object.57 58 :param url: URL for the new :class:`Request` object.58- :param **kwargs: Optional arguments that ``request`` takes.59+ :param \*\*kwargs: Optional arguments that ``request`` takes.60 """61 62 kwargs.setdefault('allow_redirects', True)63 return request('options', url, **kwargs)2 unmodified lines66 def head(url, **kwargs):67 """Sends a HEAD request. Returns :class:`Response` object.68 69 :param url: URL for the new :class:`Request` object.69- :param **kwargs: Optional arguments that ``request`` takes.70+ :param \*\*kwargs: Optional arguments that ``request`` takes.71 """72 73 kwargs.setdefault('allow_redirects', False)74 return request('head', url, **kwargs)3 unmodified lines78 """Sends a POST request. Returns :class:`Response` object.79 80 :param url: URL for the new :class:`Request` object.81 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.81- :param **kwargs: Optional arguments that ``request`` takes.82+ :param \*\*kwargs: Optional arguments that ``request`` takes.83 """84 85 return request('post', url, data=data, **kwargs)86 2 unmodified lines89 """Sends a PUT request. Returns :class:`Response` object.90 91 :param url: URL for the new :class:`Request` object.92 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.92- :param **kwargs: Optional arguments that ``request`` takes.93+ :param \*\*kwargs: Optional arguments that ``request`` takes.94 """95 96 return request('put', url, data=data, **kwargs)97 2 unmodified lines100 """Sends a PATCH request. Returns :class:`Response` object.101 102 :param url: URL for the new :class:`Request` object.103 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.103- :param **kwargs: Optional arguments that ``request`` takes.104+ :param \*\*kwargs: Optional arguments that ``request`` takes.105 """106 107 return request('patch', url, data=data, **kwargs)108 1 unmodified line110 def delete(url, **kwargs):111 """Sends a DELETE request. Returns :class:`Response` object.112 113 :param url: URL for the new :class:`Request` object.113- :param **kwargs: Optional arguments that ``request`` takes.114+ :param \*\*kwargs: Optional arguments that ``request`` takes.115 """116 117 return request('delete', url, **kwargs)modified:requests/async.py+1 added-1 removed
15 unmodified lines16 except ImportError:17 raise RuntimeError('Gevent is required for requests.async.')18 19 # Monkey-patch.20-curious_george.patch_all(thread=False)20+curious_george.patch_all(thread=False, select=False)21 22 from . import api23 24 82 unmodified linesmodified:requests/auth.py+1 added-1 removed
9 unmodified lines10 import time11 import hashlib12 13 from base64 import b64encode14-from .compat import urlparse, str, bytes14+from .compat import urlparse, str15 from .utils import randombytes, parse_dict_header16 17 18 130 unmodified linesmodified:requests/models.py+22 added-36 removed
61 unmodified lines62 hooks=None,63 config=None,64 _poolmanager=None,65 verify=None,66- session=None):66+ session=None,67+ cert=None):68 69 #: Dictionary of configurations for this request.70 self.config = dict(config or [])71 71 unmodified lines143 144 #: SSL Verification.145 self.verify = verify146 147+ #: SSL Certificate148+ self.cert = cert149+150 if headers:151 headers = CaseInsensitiveDict(self.headers)152 else:153 headers = CaseInsensitiveDict()116 unmodified lines270 timeout=self.timeout,271 _poolmanager=self._poolmanager,272 proxies=self.proxies,273 verify=self.verify,270- session=self.session274+ session=self.session,275+ cert=self.cert276 )277 278 request.send()279 r = request.response231 unmodified lines511 else:512 conn.cert_reqs = 'CERT_NONE'513 conn.ca_certs = None514 515+ if self.cert and self.verify:516+ if len(self.cert) == 2:517+ conn.cert_file = self.cert[0]518+ conn.key_file = self.cert[1]519+ else:520+ conn.cert_file = self.cert521+522 if not self.sent or anyway:523 524 if self.cookies:525 133 unmodified lines659 @property660 def ok(self):661 try:662 self.raise_for_status()651- except HTTPError:663+ except RequestException:664 return False665 return True666 667 def iter_content(self, chunk_size=10 * 1024, decode_unicode=False):14 unmodified lines682 break683 yield chunk684 self._content_consumed = True685 674- def generate_chunked():675- resp = self.raw._original_response676- fp = resp.fp677- if resp.chunk_left is not None:678- pending_bytes = resp.chunk_left679- while pending_bytes:680- chunk = fp.read(min(chunk_size, pending_bytes))681- pending_bytes -= len(chunk)682- yield chunk683- fp.read(2) # throw away crlf684- while 1:685- #XXX correct line size? (httplib has 64kb, seems insane)686- pending_bytes = fp.readline(40).strip()687- if not len(pending_bytes):688- # No content, like a HEAD request. Break out.689- break690- pending_bytes = int(pending_bytes, 16)691- if pending_bytes == 0:692- break693- while pending_bytes:694- chunk = fp.read(min(chunk_size, pending_bytes))695- pending_bytes -= len(chunk)696- yield chunk697- fp.read(2) # throw away crlf698- self._content_consumed = True699- fp.close()686+ gen = stream_untransfer(generate(), self)687 701- if getattr(getattr(self.raw, '_original_response', None), 'chunked', False):702- gen = generate_chunked()703- else:704- gen = generate()705-706- gen = stream_untransfer(gen, self)707-688 if decode_unicode:689 gen = stream_decode_response_unicode(gen, self)690 691 return gen75 unmodified lines767 768 # Decode unicode from given encoding.769 try:770 content = str(self.content, encoding, errors='replace')771+ except LookupError:772+ # A LookupError is raised if the encoding was not found which could773+ # indicate a misspelling or similar mistake.774+ #775+ # So we try blindly encoding.776+ content = str(self.content, errors='replace')777 except (UnicodeError, TypeError):778 pass779 780 return content22 unmodified linesmodified:requests/sessions.py+15 added-10 removed
50 unmodified lines51 """A Requests session."""52 53 __attrs__ = [54 'headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',55- 'params', 'config', 'verify']55+ 'params', 'config', 'verify', 'cert']56 57 58 def __init__(self,59 headers=None,4 unmodified lines64 hooks=None,65 params=None,66 config=None,67 prefetch=False,68- verify=True):68+ verify=True,69+ cert=None):70 71 self.headers = headers or {}72 self.cookies = cookies or {}73 self.auth = auth3 unmodified lines77 self.params = params or {}78 self.config = config or {}79 self.prefetch = prefetch80 self.verify = verify81+ self.cert = cert82 83 for (k, v) in list(defaults.items()):84 self.config.setdefault(k, v)85 34 unmodified lines120 hooks=None,121 return_response=True,122 config=None,123 prefetch=False,122- verify=None):124+ verify=None,125+ cert=None):126 127 """Constructs and sends a :class:`Request <Request>`.128 Returns :class:`Response <Response>` object.129 11 unmodified lines141 :param return_response: (optional) If False, an un-sent Request object will returned.142 :param config: (optional) A configuration dictionary.143 :param prefetch: (optional) if ``True``, the response content will be immediately downloaded.144 :param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.145+ :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.146 """147 148 method = str(method).upper()149 29 unmodified lines179 allow_redirects=allow_redirects,180 proxies=proxies,181 config=config,182 verify=verify,183+ cert=cert,184 _poolmanager=self.poolmanager185 )186 187 # Merge local kwargs with session kwargs.29 unmodified lines217 def get(self, url, **kwargs):218 """Sends a GET request. Returns :class:`Response` object.219 220 :param url: URL for the new :class:`Request` object.216- :param **kwargs: Optional arguments that ``request`` takes.221+ :param \*\*kwargs: Optional arguments that ``request`` takes.222 """223 224 kwargs.setdefault('allow_redirects', True)225 return self.request('get', url, **kwargs)2 unmodified lines228 def options(self, url, **kwargs):229 """Sends a OPTIONS request. Returns :class:`Response` object.230 231 :param url: URL for the new :class:`Request` object.227- :param **kwargs: Optional arguments that ``request`` takes.232+ :param \*\*kwargs: Optional arguments that ``request`` takes.233 """234 235 kwargs.setdefault('allow_redirects', True)236 return self.request('options', url, **kwargs)2 unmodified lines239 def head(self, url, **kwargs):240 """Sends a HEAD request. Returns :class:`Response` object.241 242 :param url: URL for the new :class:`Request` object.238- :param **kwargs: Optional arguments that ``request`` takes.243+ :param \*\*kwargs: Optional arguments that ``request`` takes.244 """245 246 kwargs.setdefault('allow_redirects', False)247 return self.request('head', url, **kwargs)3 unmodified lines251 """Sends a POST request. Returns :class:`Response` object.252 253 :param url: URL for the new :class:`Request` object.254 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.250- :param **kwargs: Optional arguments that ``request`` takes.255+ :param \*\*kwargs: Optional arguments that ``request`` takes.256 """257 258 return self.request('post', url, data=data, **kwargs)259 2 unmodified lines262 """Sends a PUT request. Returns :class:`Response` object.263 264 :param url: URL for the new :class:`Request` object.265 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.261- :param **kwargs: Optional arguments that ``request`` takes.266+ :param \*\*kwargs: Optional arguments that ``request`` takes.267 """268 269 return self.request('put', url, data=data, **kwargs)270 2 unmodified lines273 """Sends a PATCH request. Returns :class:`Response` object.274 275 :param url: URL for the new :class:`Request` object.276 :param data: (optional) Dictionary or bytes to send in the body of the :class:`Request`.272- :param **kwargs: Optional arguments that ``request`` takes.277+ :param \*\*kwargs: Optional arguments that ``request`` takes.278 """279 280 return self.request('patch', url, data=data, **kwargs)281 1 unmodified line283 def delete(self, url, **kwargs):284 """Sends a DELETE request. Returns :class:`Response` object.285 286 :param url: URL for the new :class:`Request` object.282- :param **kwargs: Optional arguments that ``request`` takes.287+ :param \*\*kwargs: Optional arguments that ``request`` takes.288 """289 290 return self.request('delete', url, **kwargs)291 14 unmodified linesmodified:requests/utils.py+9 added-1 removed
12 unmodified lines13 import codecs14 import os15 import random16 import re17-import traceback17 import zlib18 from netrc import netrc, NetrcParseError19 20 from .compat import parse_http_list as _parse_list_header3 unmodified lines24 25 NETRC_FILES = ('.netrc', '_netrc')26 27 28+def dict_to_sequence(d):29+ """Returns an internal sequence dictionary update."""30+31+ if hasattr(d, 'items'):32+ d = d.items()33+34+ return d35+36+37 def get_netrc_auth(url):38 """Returns the Requests tuple auth for a given url from netrc."""39 40 locations = (os.path.expanduser('~/{0}'.format(f)) for f in NETRC_FILES)431 unmodified linesmodified:tests/test_requests_async.py+6 added
6 unmodified lines7 8 import sys9 import unittest10 11+import select12+has_poll = hasattr(select, "poll")13+14 from requests import async15 import envoy16 17 sys.path.append('.')41 unmodified lines59 60 async.map61 async.send62 63+ def test_select_poll(self):64+ """Test to make sure we don't overwrite the poll"""65+ self.assertEqual(hasattr(select, "poll"), has_poll)66 67 if __name__ == '__main__':68 unittest.main()modified:AUTHORS.rst+4 added
86 unmodified lines87 - Brendan Maguire <maguire.brendan@gmail.com>88 - Chris Dary89 - Danver Braganza <danverbraganza@gmail.com>90 - Max Countryman91+- Nick Chadwick92+- Jonathan Drosdeck93+- Jiri Machalek94+- Steve Pulecmodified:HISTORY.rst+8 added
1 History2 -------3 4+0.11.0 (2012-03-14)5++++++++++++++++++++6+7+* Private SSL Certificate support8+* Remove select.poll from Gevent monkeypatching9+* Remove redundant generator for chunked transfer encoding10+* Fix: Response.ok raises Timeout Exception in safe_mode11+12 0.10.8 (2012-03-09)13 +++++++++++++++++++14 15 * Generate chunked ValueError fix410 unmodified linesmodified:README.rst+1 added-1 removed
71 unmodified lines72 #. Write a test which shows that the bug was fixed or that the feature works as expected.73 #. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS_.74 75 .. _`the repository`: http://github.com/kennethreitz/requests76-.. _AUTHORS: http://github.com/kennethreitz/requests/blob/master/AUTHORS76+.. _AUTHORS: https://github.com/kennethreitz/requests/blob/develop/AUTHORS.rst