Skip to content
Myr

Merge branch 'master' of github.com:kennethreitz/requests

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 1cb759a, 552ab7a · Browse files · 13 files+229 added−34 removed
This commit

State

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

Diff stats

13 files+229 added−34 removed

  • tests:+75 added−3 removed
  • other:+154 added−31 removed

13 files+229 added−34 removed

added:docs/_static/requests-logo-small.pngbinary

A binary file, added.

modified:docs/_templates/sidebarintro.html+1 added
modified:docs/_templates/sidebarlogo.html+1 added
modified:docs/user/advanced.rst+1 added-1 removed
225 unmodified lines
226By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.227228You can also specify a local cert to use as client side certificate, as a single229file (containing the private key and the certificate) or as a tuple of both230file's path::230files' paths::231232 >>> requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))233 <Response [200]>234
755 unmodified lines
modified:docs/index.rst+12 added-12 removed
66 unmodified lines
67PayPal, NPR, Obama for America, Transifex, Native Instruments, The Washington68Post, Twitter, SoundCloud, Kippt, Sony, and Federal U.S.69Institutions that prefer to be unnamed claim to use Requests internally.7071**Armin Ronacher**72 Requests is the perfect example how beautiful an API can be with the73 right level of abstraction.71**Armin Ronacher**—72 *Requests is the perfect example how beautiful an API can be with the73 right level of abstraction.*7475**Matt DeBoard**76 I'm going to get `@kennethreitz <https://twitter.com/kennethreitz>`_'s Python requests module tattooed77 on my body, somehow. The whole thing.75**Matt DeBoard**—76 *I'm going to get `@kennethreitz <https://twitter.com/kennethreitz>`_'s Python requests module tattooed77 on my body, somehow. The whole thing.*7879**Daniel Greenfeld**80 Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to81 `@kennethreitz <https://twitter.com/kennethreitz>`_'s request library. Today has been AWESOME.79**Daniel Greenfeld**—80 *Nuked a 1200 LOC spaghetti code library with 10 lines of code thanks to81 `@kennethreitz <https://twitter.com/kennethreitz>`_'s request library. Today has been AWESOME.*8283**Kenny Meyers**84 Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,85 simple, Pythonic.83**Kenny Meyers**—84 *Python HTTP: When in doubt, or when not in doubt, use Requests. Beautiful,85 simple, Pythonic.*8687Requests is one of the most downloaded Python packages of all time, pulling in88over 11,000,000 downloads every month. All the cool kids are doing it!89
87 unmodified lines
modified:requests/api.py+4 added-4 removed
17 unmodified lines
1819 :param method: method for the new :class:`Request` object.20 :param url: URL for the new :class:`Request` object.21 :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.22 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.22 :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.23 :param json: (optional) json data to send in the body of the :class:`Request`.24 :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.25 :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.26 :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
72 unmodified lines
99def post(url, data=None, json=None, **kwargs):100 """Sends a POST request.101102 :param url: URL for the new :class:`Request` object.103 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.103 :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.104 :param json: (optional) json data to send in the body of the :class:`Request`.105 :param \*\*kwargs: Optional arguments that ``request`` takes.106 :return: :class:`Response <Response>` object107 :rtype: requests.Response
5 unmodified lines
113def put(url, data=None, **kwargs):114 """Sends a PUT request.115116 :param url: URL for the new :class:`Request` object.117 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.117 :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.118 :param json: (optional) json data to send in the body of the :class:`Request`.119 :param \*\*kwargs: Optional arguments that ``request`` takes.120 :return: :class:`Response <Response>` object121 :rtype: requests.Response
5 unmodified lines
127def patch(url, data=None, **kwargs):128 """Sends a PATCH request.129130 :param url: URL for the new :class:`Request` object.131 :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.131 :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.132 :param json: (optional) json data to send in the body of the :class:`Request`.133 :param \*\*kwargs: Optional arguments that ``request`` takes.134 :return: :class:`Response <Response>` object135 :rtype: requests.Response
15 unmodified lines
modified:requests/models.py+21 added-2 removed
657 unmodified lines
658 def __repr__(self):659 return '<Response [%s]>' % (self.status_code)660661 def __bool__(self):662 """Returns true if :attr:`status_code` is 'OK'."""662 """Returns True if :attr:`status_code` is less than 400.663664 This attribute checks if the status code of the response is between665 400 and 600 to see if there was a client error or a server error. If666 the status code, is between 200 and 400, this will return True. This667 is **not** a check to see if the response code is ``200 OK``.668 """669 return self.ok670671 def __nonzero__(self):666 """Returns true if :attr:`status_code` is 'OK'."""672 """Returns True if :attr:`status_code` is less than 400.673674 This attribute checks if the status code of the response is between675 400 and 600 to see if there was a client error or a server error. If676 the status code, is between 200 and 400, this will return True. This677 is **not** a check to see if the response code is ``200 OK``.678 """679 return self.ok680681 def __iter__(self):682 """Allows you to use a response as an iterator."""683 return self.iter_content(128)684685 @property686 def ok(self):687 """Returns True if :attr:`status_code` is less than 400.688689 This attribute checks if the status code of the response is between690 400 and 600 to see if there was a client error or a server error. If691 the status code, is between 200 and 400, this will return True. This692 is **not** a check to see if the response code is ``200 OK``.693 """694 try:695 self.raise_for_status()696 except HTTPError:697 return False
244 unmodified lines
modified:requests/structures.py+89 added
6 unmodified lines
7Data structures that power Requests.8"""910import collections11import time1213from .compat import OrderedDict1415current_time = getattr(time, 'monotonic', time.time)161718class CaseInsensitiveDict(collections.MutableMapping):19 """A case-insensitive ``dict``-like object.2021 Implements all methods and operations of
83 unmodified lines
105 return self.__dict__.get(key, None)106107 def get(self, key, default=None):108 return self.__dict__.get(key, default)109110111class TimedCacheManaged(object):112 """113 Wrap a function call in a timed cache114 """115 def __init__(self, fnc):116 self.fnc = fnc117 self.cache = TimedCache()118119 def __call__(self, *args, **kwargs):120 key = args[0]121 found = None122 try:123 found = self.cache[key]124 except KeyError:125 found = self.fnc(key, **kwargs)126 self.cache[key] = found127128 return found129130131class TimedCache(collections.MutableMapping):132 """133 Evicts entries after expiration_secs. If none are expired and maxlen is hit,134 will evict the oldest cached entry135 """136 def __init__(self, maxlen=32, expiration_secs=60):137 """138 :param maxlen: most number of entries to hold on to139 :param expiration_secs: the number of seconds to hold on140 to entries141 """142 self.maxlen = maxlen143 self.expiration_secs = expiration_secs144 self._dict = OrderedDict()145146 def __repr__(self):147 return '<TimedCache maxlen:%d len:%d expiration_secs:%d>' % \148 (self.maxlen, len(self._dict), self.expiration_secs)149150 def __iter__(self):151 return ((key, value[1]) for key, value in self._dict.items())152153 def __delitem__(self, item):154 del self._dict[item]155156 def __getitem__(self, key):157 """158 Look up an item in the cache. If the item159 has already expired, it will be invalidated and not returned160161 :param key: which entry to look up162 :return: the value in the cache, or None163 """164 occurred, value = self._dict[key]165 now = int(current_time())166167 if now - occurred > self.expiration_secs:168 del self._dict[key]169 raise KeyError(key)170 else:171 return value172173 def __setitem__(self, key, value):174 """175 Locates the value at lookup key, if cache is full, will evict the176 oldest entry177178 :param key: the key to search the cache for179 :param value: the value to be added to the cache180 """181 now = int(current_time())182183 while len(self._dict) >= self.maxlen:184 self._dict.popitem(last=False)185186 self._dict[key] = (now, value)187188 def __len__(self):189 """:return: the length of the cache"""190 return len(self._dict)191192 def clear(self):193 """Clears the cache"""194 return self._dict.clear()
modified:requests/utils.py+22 added-10 removed
26 unmodified lines
27from .compat import (28 quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,29 proxy_bypass, urlunparse, basestring, integer_types)30from .cookies import RequestsCookieJar, cookiejar_from_dict31from .structures import CaseInsensitiveDict31from .structures import CaseInsensitiveDict, TimedCache, TimedCacheManaged32from .exceptions import (33 InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)3435_hush_pyflakes = (RequestsCookieJar,)
55 unmodified lines
91 current_position = total_length92 else:93 if hasattr(o, 'seek') and total_length is None:94 # StringIO and BytesIO have seek but no useable fileno95 try:96 # seek to end of file97 o.seek(0, 2)98 total_length = o.tell()9996 # seek to end of file97 o.seek(0, 2)98 total_length = o.tell()100 # seek back to current position to support101 # partially read file-like objects102 o.seek(current_position or 0)103 except (OSError, IOError):104 total_length = 0105100 # seek back to current position to support101 # partially read file-like objects102 o.seek(current_position or 0)103106 if total_length is None:107 total_length = 0108109 return max(0, total_length - current_position)
468 unmodified lines
578 else:579 os.environ[env_name] = old_value580581582@TimedCacheManaged583def _proxy_bypass_cached(netloc):584 """585 Looks for netloc in the cache, if not found, will call proxy_bypass586 for the netloc and store its result in the cache587588 :rtype: bool589 """590 return proxy_bypass(netloc)591592def should_bypass_proxies(url, no_proxy):593 """594 Returns whether we should bypass proxies or not.595
39 unmodified lines
635 # exceptions we've seen, though: this call failing in other ways can reveal636 # legitimate problems.637 with set_environ('no_proxy', no_proxy_arg):638 try:627 bypass = proxy_bypass(netloc)639 bypass = _proxy_bypass_cached(netloc)640 except (TypeError, socket.gaierror):641 bypass = False642643 if bypass:
214 unmodified lines
858 if body_seek is not None and isinstance(prepared_request._body_position, integer_types):859 try:860 body_seek(prepared_request._body_position)861 except (IOError, OSError):850 raise UnrewindableBodyError("An error occured when rewinding request "862 raise UnrewindableBodyError("An error occurred when rewinding request "863 "body for redirect.")864 else:865 raise UnrewindableBodyError("Unable to rewind request body for redirect.")
modified:tests/test_requests.py+2 added-2 removed
1544 unmodified lines
15451546 def tell(self):1547 return 015481549 def seek(self, pos):1549 def seek(self, pos, whence=0):1550 raise OSError()15511552 def __iter__(self):1553 return
5 unmodified lines
15591560 with pytest.raises(UnrewindableBodyError) as e:1561 requests.utils.rewind_body(prep)15621563 assert 'error occured when rewinding request body' in str(e)1563 assert 'error occurred when rewinding request body' in str(e)15641565 def test_rewind_body_failed_tell(self):1566 class BadFileObj:1567 def __init__(self, data):
771 unmodified lines
modified:tests/test_structures.py+73 added-1 removed
1# -*- coding: utf-8 -*-23import pytest45from requests.structures import CaseInsensitiveDict, LookupDict5from requests.structures import CaseInsensitiveDict, LookupDict, TimedCache, TimedCacheManaged678class TestCaseInsensitiveDict:9
63 unmodified lines
7374 @get_item_parameters75 def test_get(self, key, value):76 assert self.lookup_dict.get(key) == value777879class TestTimedCache(object):80 @pytest.fixture(autouse=True)81 def setup(self):82 self.any_value = 'some value'83 self.expiration_secs = 6084 self.cache = TimedCache(expiration_secs=self.expiration_secs)85 yield86 self.cache.clear()8788 def test_get(self):89 self.cache['a'] = self.any_value90 assert self.cache['a'] is self.any_value9192 def test_repr(self):93 repr = str(self.cache)94 assert repr == '<TimedCache maxlen:32 len:0 expiration_secs:60>'9596 def test_get_expired_item(self, mocker):97 self.cache = TimedCache(maxlen=1, expiration_secs=self.expiration_secs)9899 mocker.patch('requests.structures.current_time', lambda: 0)100 self.cache['a'] = self.any_value101 mocker.patch('requests.structures.current_time', lambda: self.expiration_secs + 1)102 assert self.cache.get('a') is None103104 def test_evict_first_entry_when_full(self, mocker):105 self.cache = TimedCache(maxlen=2, expiration_secs=2)106 mocker.patch('requests.structures.current_time', lambda: 0)107 self.cache['a'] = self.any_value108 mocker.patch('requests.structures.current_time', lambda: 1)109 self.cache['b'] = self.any_value110 mocker.patch('requests.structures.current_time', lambda: 3)111 self.cache['c'] = self.any_value112 assert len(self.cache) is 2113 with pytest.raises(KeyError, message='Expected key not found'):114 self.cache['a']115 assert self.cache['b'] is self.any_value116 assert self.cache['c'] is self.any_value117118 def test_delete_item_removes_item(self):119 self.cache['a'] = self.any_value120 del self.cache['a']121 with pytest.raises(KeyError, message='Expected key not found'):122 self.cache['a']123124 def test_iterating_hides_timestamps(self):125 self.cache['a'] = 1126 self.cache['b'] = 2127 expected = [('a', 1), ('b', 2)]128 actual = [(key, val) for key, val in self.cache]129 assert expected == actual130131132class TestTimedCacheManagedDecorator(object):133 def test_caches_repeated_calls(self, mocker):134 mocker.patch('requests.structures.current_time', lambda: 0)135136 nonlocals = {'value': 0}137138 @TimedCacheManaged139 def some_method(x):140 nonlocals['value'] = nonlocals['value'] + x141 return nonlocals['value']142143 first_result = some_method(1)144 assert first_result is 1145 second_result = some_method(1)146 assert second_result is 1147 third_result = some_method(2)148 assert third_result is 3
modified:AUTHORS.rst+1 added
176 unmodified lines
177- Andrii Soldatenko (`@a_soldatenko <https://github.com/andriisoldatenko>`_)178- Moinuddin Quadri <moin18@gmail.com> (`@moin18 <https://github.com/moin18>`_)179- Matt Kohl (`@mattkohl <https://github.com/mattkohl>`_)180- Jonathan Vanasco (`@jvanasco <https://github.com/jvanasco>`_)181- David Fontenot (`@davidfontenot <https://github.com/davidfontenot>`_)182
modified:README.rst+2 added-2 removed
26 unmodified lines
2728Requests is the only *Non-GMO* HTTP library for Python, safe for human29consumption.3031**Warning:** Recreational use of other HTTP libraries may result in dangerous side-effects,31**Warning:** Recreational use of the Python standard library for HTTP may result in dangerous side-effects,32including: security vulnerabilities, verbose code, reinventing the wheel,33constantly reading documentation, depression, headaches, or even death.3435Behold, the power of Requests:
13 unmodified lines
49 {u'disk_usage': 368627, u'private_gists': 484, ...}5051See `the similar code, sans Requests <https://gist.github.com/973705>`_.5253.. image:: http://docs.python-requests.org/en/master/_static/requests-sidebar.png53.. image:: https://raw.githubusercontent.com/kennethreitz/requests/master/docs/_static/requests-logo-small.png54 :target: http://docs.python-requests.org/555657Requests allows you to send *organic, grass-fed* HTTP/1.1 requests, without the
62 unmodified lines