Skip to content
Myr

Merge remote-tracking branch 'origin/master'

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 d7e8073, 65a0fd8 · Browse files · 22 files+269 added−70 removed
This commit

State

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

Diff stats

22 files+269 added−70 removed

  • other:+269 added−70 removed

22 files+269 added−70 removed

modified:docs/_templates/sidebarintro.html+1 added-2 removed
modified:docs/dev/todo.rst+5 added
51 unmodified lines
52Are you crazy?53--------------5455- SPDY support would be awesome. No C extensions.5657Downstream Repackaging58--------------------5960If you are repackaging Requests, please note that you must also redistribute the ``cacerts.pem`` file in order to get correct SSL functionality.
modified:docs/user/advanced.rst+20 added-2 removed
47 unmodified lines
48Request and Response Objects49----------------------------5051Whenever a call is made to requests.*() you are doing two major things. First,52you are constructing a ``Request`` object which will be sent of to a server52you are constructing a ``Request`` object which will be sent off to a server53to request or query some resource. Second, a ``Response`` object is generated54once ``requests`` gets a response back from the server. The response object55contains all of the information returned by the server and also contains the56``Request`` object you created originally. Here is a simple request to get some
210 unmodified lines
267268 >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))269 <Response [200]>270271.. _streaming-requests272273Streaming Requests274------------------275276With ``requests.Response.iter_lines()`` you can easily iterate over streaming
3 unmodified lines
280281 import json282 import requests283282 r = requests.post('http://httpbin.org/stream/20', stream=True)284 r = requests.get('http://httpbin.org/stream/20', stream=True)285286 for line in r.iter_lines():287288 # filter out keep-alive new lines
286 unmodified lines
575576.. _`described here`: http://kennethreitz.org/exposures/the-future-of-python-http577.. _`urllib3`: https://github.com/shazow/urllib3578579Blocking Or Non-Blocking?580-------------------------581582With the default Transport Adapter in place, Requests does not provide any kind583of non-blocking IO. The ``Response.content`` property will block until the584entire response has been downloaded. If you require more granularity, the585streaming features of the library (see :ref:`streaming-requests`) allow you to586retrieve smaller quantities of the response at a time. However, these calls587will still block.588589If you are concerned about the use of blocking IO, there are lots of projects590out there that combine Requests with one of Python's asynchronicity frameworks.591Two excellent examples are `grequests`_ and `requests-futures`_.592593.. _`grequests`: https://github.com/kennethreitz/grequests594.. _`requests-futures`: https://github.com/ross/requests-futures
modified:docs/user/quickstart.rst+7 added-6 removed
258 unmodified lines
259260 >>> r.status_code == requests.codes.ok261 True262263If we made a bad request (non-200 response), we can raise it with263If we made a bad request (a 4XX client error or 5XX server error response), we can raise it with264:class:`Response.raise_for_status()`::265266 >>> bad_r = requests.get('http://httpbin.org/status/404')267 >>> bad_r.status_code
130 unmodified lines
398Errors and Exceptions399---------------------400401In the event of a network problem (e.g. DNS failure, refused connection, etc),402Requests will raise a :class:`ConnectionError` exception.402Requests will raise a :class:`~requests.exceptions.ConnectionError` exception.403404In the event of the rare invalid HTTP response, Requests will raise405an :class:`HTTPError` exception.404In the event of the rare invalid HTTP response, Requests will raise an405:class:`~requests.exceptions.HTTPError` exception.406407If a request times out, a :class:`Timeout` exception is raised.407If a request times out, a :class:`~requests.exceptions.Timeout` exception is408raised.409410If a request exceeds the configured number of maximum redirections, a410:class:`TooManyRedirects` exception is raised.411:class:`~requests.exceptions.TooManyRedirects` exception is raised.412413All exceptions that Requests explicitly raises inherit from414:class:`requests.exceptions.RequestException`.415
3 unmodified lines
modified:requests/packages/urllib3/contrib/ntlmpool.py+1 added-1 removed
31 unmodified lines
3233 def __init__(self, user, pw, authurl, *args, **kwargs):34 """35 authurl is a random URL on the server that is protected by NTLM.36 user is the Windows user, probably in the DOMAIN\username format.36 user is the Windows user, probably in the DOMAIN\\username format.37 pw is the password for the user.38 """39 super(NTLMConnectionPool, self).__init__(*args, **kwargs)40 self.authurl = authurl
80 unmodified lines
modified:requests/packages/urllib3/contrib/pyopenssl.py+3 added
113 unmodified lines
114115 def sendall(self, data):116 return self.connection.sendall(data)117118 def close(self):119 return self.connection.shutdown()120121 def getpeercert(self, binary_form=False):122 x509 = self.connection.get_peer_certificate()123 if not x509:124 raise ssl.SSLError('')
46 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+2 added-1 removed
108 unmodified lines
109 if resolved_cert_reqs != ssl.CERT_NONE:110 if self.assert_fingerprint:111 assert_fingerprint(self.sock.getpeercert(binary_form=True),112 self.assert_fingerprint)113 else:113 elif self.assert_hostname is not False:114 match_hostname(self.sock.getpeercert(),115 self.assert_hostname or self.host)116117## Pool objects
394 unmodified lines
512 instead of :class:`httplib.HTTPSConnection`.513514 :class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,515 ``assert_hostname`` and ``host`` in this order to verify connections.516 If ``assert_hostname`` is False, no verification is done.517518 The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs`` and519 ``ssl_version`` are only used if :mod:`ssl` is available and are fed into520 :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket
78 unmodified lines
modified:requests/packages/urllib3/filepost.py+1 added-1 removed
1# urllib3/filepost.py2# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php6
92 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+9 added
4 unmodified lines
5# the MIT License: http://www.opensource.org/licenses/mit-license.php67import logging89try: # Python 310 from urllib.parse import urljoin11except ImportError:12 from urlparse import urljoin1314from ._collections import RecentlyUsedContainer15from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool16from .connectionpool import connection_from_url, port_by_scheme17from .request import RequestMethods
131 unmodified lines
149 redirect_location = redirect and response.get_redirect_location()150 if not redirect_location:151 return response152153 # Support relative URLs for redirecting.154 redirect_location = urljoin(url, redirect_location)155156 # RFC 2616, Section 10.3.4157 if response.status == 303:158 method = 'GET'159160 log.info("Redirecting %s -> %s" % (url, redirect_location))
41 unmodified lines
modified:requests/packages/urllib3/request.py+1 added-1 removed
28 unmodified lines
29 :meth:`.request_encode_url` is for sending requests whose fields are encoded30 in the URL (such as GET, HEAD, DELETE).3132 :meth:`.request_encode_body` is for sending requests whose fields are33 encoded in the *body* of the request using multipart or www-orm-urlencoded33 encoded in the *body* of the request using multipart or www-form-urlencoded34 (such as for POST, PUT, PATCH).3536 :meth:`.request` is for making any kind of request, it will look up the37 appropriate encoding format and use one of the above two methods to make
105 unmodified lines
modified:requests/packages/urllib3/response.py+59 added-2 removed
1# urllib3/response.py2# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)2# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)3#4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php678import logging9import zlib10import io1112from .exceptions import DecodeError13from .packages.six import string_types as basestring, binary_type14from .util import is_fp_closed151617log = logging.getLogger(__name__)18
30 unmodified lines
4950 return DeflateDecoder()515251class HTTPResponse(object):53class HTTPResponse(io.IOBase):54 """55 HTTP Response container.5657 Backwards-compatible to httplib's HTTPResponse but the response ``body`` is
143 unmodified lines
201 finally:202 if self._original_response and self._original_response.isclosed():203 self.release_conn()204205 def stream(self, amt=2**16, decode_content=None):206 """207 A generator wrapper for the read() method. A call will block until208 ``amt`` bytes have been read from the connection or until the209 connection is closed.210211 :param amt:212 How much of the content to read. The generator will return up to213 much data per iteration, but may return less. This is particularly214 likely when using compressed data. However, the empty string will215 never be returned.216217 :param decode_content:218 If True, will attempt to decode the body based on the219 'content-encoding' header.220 """221 while not is_fp_closed(self._fp):222 data = self.read(amt=amt, decode_content=decode_content)223224 if data:225 yield data226227228 @classmethod229 def from_httplib(ResponseCls, r, **response_kw):230 """231 Given an :class:`httplib.HTTPResponse` instance ``r``, return a
31 unmodified lines
263 return self.headers264265 def getheader(self, name, default=None):266 return self.headers.get(name, default)267268 # Overrides from io.IOBase269 def close(self):270 if not self.closed:271 self._fp.close()272273 @property274 def closed(self):275 if self._fp is None:276 return True277 elif hasattr(self._fp, 'closed'):278 return self._fp.closed279 elif hasattr(self._fp, 'isclosed'): # Python 2280 return self._fp.isclosed()281 else:282 return True283284 def fileno(self):285 if self._fp is None:286 raise IOError("HTTPResponse has no file to get a fileno from")287 elif hasattr(self._fp, "fileno"):288 return self._fp.fileno()289 else:290 raise IOError("The file-like object this HTTPResponse is wrapped "291 "around has no file descriptor")292293 def flush(self):294 if self._fp is not None and hasattr(self._fp, 'flush'):295 return self._fp.flush()296297 def readable(self):298 return True
modified:requests/packages/urllib3/util.py+14 added-1 removed
29 unmodified lines
30 from ssl import HAS_SNI # Has SNI?31except ImportError:32 pass333434from .packages import six35from .exceptions import LocationParseError, SSLError3637
301 unmodified lines
339 raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'340 .format(hexlify(fingerprint_bytes),341 hexlify(cert_digest)))342343def is_fp_closed(obj):344 """345 Checks whether a given file-like object is closed.346347 :param obj:348 The file-like object to check.349 """350 if hasattr(obj, 'fp'):351 # Object is a container for another file-like object that gets released352 # on exhaustion (e.g. HTTPResponse)353 return obj.fp is None354355 return obj.closed356357358if SSLContext is not None: # Python 3.2+359 def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,360 ca_certs=None, server_hostname=None,361 ssl_version=None):
30 unmodified lines
modified:requests/adapters.py+4 added-4 removed
116 unmodified lines
117 :param url: The requested URL.118 :param verify: Whether we should actually verify the certificate.119 :param cert: The SSL certificate to verify.120 """121 if url.startswith('https') and verify:121 if url.lower().startswith('https') and verify:122123 cert_loc = None124125 # Allow self-specified cert location.
63 unmodified lines
189 :param url: The URL to connect to.190 :param proxies: (optional) A Requests-style dictionary of proxies used on this request.191 """192 proxies = proxies or {}193 proxy = proxies.get(urlparse(url).scheme)193 proxy = proxies.get(urlparse(url.lower()).scheme)194195 if proxy:196 proxy = prepend_scheme_if_needed(proxy, urlparse(url).scheme)196 proxy = prepend_scheme_if_needed(proxy, urlparse(url.lower()).scheme)197 conn = ProxyManager(self.poolmanager.connection_from_url(proxy))198 else:199 conn = self.poolmanager.connection_from_url(url)199 conn = self.poolmanager.connection_from_url(url.lower())200201 return conn202203 def close(self):
139 unmodified lines
modified:requests/compat.py+2 added-2 removed
81 unmodified lines
82# Specifics83# ---------8485if is_py2:86 from urllib import quote, unquote, quote_plus, unquote_plus, urlencode86 from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass87 from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag88 from urllib2 import parse_http_list89 import cookielib90 from Cookie import Morsel
8 unmodified lines
99100101elif is_py3:102 from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag103 from urllib.request import parse_http_list103 from urllib.request import parse_http_list, getproxies, proxy_bypass104 from http import cookiejar as cookielib105 from http.cookies import Morsel106 from io import StringIO107 from collections import OrderedDict
6 unmodified lines
modified:requests/cookies.py+15 added-5 removed
4 unmodified lines
56requests.utils imports from here, so be careful with imports.7"""89import time10import collections11from .compat import cookielib, urlparse, Morsel1213try:
244 unmodified lines
258 def __delitem__(self, name):259 """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""260 remove_cookie_by_name(self, name)261262 def set_cookie(self, cookie, *args, **kwargs):263 if cookie.value.startswith('"') and cookie.value.endswith('"'):264 cookie.value = cookie.value.replace('\\"', '')265 return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)266267 def update(self, other):268 """Updates this jar with cookies from another CookieJar or dict-like"""269 if isinstance(other, cookielib.CookieJar):270 for cookie in other:
88 unmodified lines
359360361def morsel_to_cookie(morsel):362 """Convert a Morsel object into a Cookie containing the one k/v pair."""363 expires = None364 if morsel["max-age"]:365 expires = time.time() + morsel["max-age"]366 elif morsel['expires']:367 expires = morsel['expires']368 if type(expires) == type(""):369 time_template = "%a, %d-%b-%Y %H:%M:%S GMT"370 expires = time.mktime(time.strptime(expires, time_template))371 c = create_cookie(372 name=morsel.key,373 value=morsel.value,374 version=morsel['version'] or 0,375 port=None,362 port_specified=False,376 domain=morsel['domain'],364 domain_specified=bool(morsel['domain']),365 domain_initial_dot=morsel['domain'].startswith('.'),377 path=morsel['path'],367 path_specified=bool(morsel['path']),378 secure=bool(morsel['secure']),369 expires=morsel['max-age'] or morsel['expires'],379 expires=expires,380 discard=False,381 comment=morsel['comment'],382 comment_url=bool(morsel['comment']),383 rest={'HttpOnly': morsel['httponly']},
16 unmodified lines
modified:requests/models.py+14 added-7 removed
362 unmodified lines
363364 try:365 length = super_len(data)366 except (TypeError, AttributeError):367 length = False367 length = None368369 if is_stream:370 body = data371372 if files:373 raise NotImplementedError('Streamed bodies and files are mutually exclusive.')374375 if length:375 if length is not None:376 self.headers['Content-Length'] = str(length)377 else:378 self.headers['Transfer-Encoding'] = 'chunked'379 # Check if file, fo, generator, iterator.
156 unmodified lines
536 # simulate reading small chunks of the content537 return iter_slices(self._content, chunk_size)538539 def generate():540 try:541 # Special case for urllib3.542 for chunk in self.raw.stream(chunk_size, decode_content=True):543 yield chunk544 except AttributeError:545 # Standard file-like object.540 while 1:541 chunk = self.raw.read(chunk_size, decode_content=True)542 if not chunk:543 break544 yield chunk546 while 1:547 chunk = self.raw.read(chunk_size)548 if not chunk:549 break550 yield chunk551552 self._content_consumed = True553554 gen = generate()555
138 unmodified lines
modified:requests/sessions.py+15 added-12 removed
69 unmodified lines
70 verify=True, cert=None, proxies=None):71 """Receives a Response. Returns a generator of Responses."""7273 i = 074 prepared_request = PreparedRequest()75 prepared_request.body = req.body76 prepared_request.headers = req.headers.copy()77 prepared_request.hooks = req.hooks78 prepared_request.method = req.method79 prepared_request.url = req.url7475 # ((resp.status_code is codes.see_other))76 while (('location' in resp.headers and resp.status_code in REDIRECT_STATI)):77 prepared_request = PreparedRequest()78 prepared_request.body = req.body79 prepared_request.headers = req.headers.copy()80 prepared_request.hooks = req.hooks8182 resp.content # Consume socket so it can be released8384 if i >= self.max_redirects:
2 unmodified lines
87 # Release the connection back into the pool.88 resp.close()8990 url = resp.headers['location']93 method = prepared_request.method91 method = req.method9293 # Handle redirection without scheme (see: RFC 1808 Section 4)94 if url.startswith('//'):95 parsed_rurl = urlparse(resp.url)96 url = '%s:%s' % (parsed_rurl.scheme, url)9798 # The scheme should be lower case...99 if '://' in url:100 scheme, uri = url.split('://', 1)101 url = '%s://%s' % (scheme.lower(), uri)102103 # Facilitate non-RFC2616-compliant 'location' headers104 # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')105 # Compliant with RFC3986, we percent encode the url.106 if not urlparse(url).netloc:
4 unmodified lines
111 prepared_request.url = url112113 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4114 if (resp.status_code == codes.see_other and112 prepared_request.method != 'HEAD'):115 method != 'HEAD'):116 method = 'GET'117118 # Do what the browsers do, despite standards...119 if (resp.status_code in (codes.moved, codes.found) and117 prepared_request.method not in ('GET', 'HEAD')):120 method not in ('GET', 'HEAD')):121 method = 'GET'122123 prepared_request.method = method124
163 unmodified lines
288 env_proxies = get_environ_proxies(url) or {}289 for (k, v) in env_proxies.items():290 proxies.setdefault(k, v)291289 # Set environment's basic authentication.290 if not auth:292 # Set environment's basic authentication if not explicitly set.293 if not auth and not self.auth:294 auth = get_netrc_auth(url)295296 # Look for configuration.297 if not verify and verify is not False:
171 unmodified lines
469 def get_adapter(self, url):470 """Returns the appropriate connnection adapter for the given URL."""471 for (prefix, adapter) in self.adapters.items():472470 if url.startswith(prefix):473 if url.lower().startswith(prefix):474 return adapter475476 # Nothing matches :-/477 raise InvalidSchema("No connection adapters were found for '%s'" % url)
27 unmodified lines
modified:requests/status_codes.py+2 added-1 removed
16 unmodified lines
17 204: ('no_content',),18 205: ('reset_content', 'reset'),19 206: ('partial_content', 'partial'),20 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),21 208: ('im_used',),21 208: ('already_reported',),22 226: ('im_used',),2324 # Redirection.25 300: ('multiple_choices',),26 301: ('moved_permanently', 'moved', '\\o-'),
62 unmodified lines
modified:requests/utils.py+14 added-16 removed
20 unmodified lines
21from . import __version__22from . import certs23from .compat import parse_http_list as _parse_list_header24from .compat import quote, urlparse, bytes, str, OrderedDict, urlunparse25from .compat import getproxies, proxy_bypass26from .cookies import RequestsCookieJar, cookiejar_from_dict27from .structures import CaseInsensitiveDict2829_hush_pyflakes = (RequestsCookieJar,)
271 unmodified lines
301 for chunk in iterator:302 rv = decoder.decode(chunk)303 if rv:304 yield rv304 rv = decoder.decode('', final=True)305 rv = decoder.decode(b'', final=True)306 if rv:307 yield rv308309
76 unmodified lines
386387def get_environ_proxies(url):388 """Return a dict of environment proxies."""389389 proxy_keys = [390 'all',391 'http',392 'https',393 'ftp',394 'socks'395 ]396390 get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())391392 # First check whether no_proxy is defined. If it is, check that the URL393 # we're getting isn't in the no_proxy list.394 no_proxy = get_proxy('no_proxy')395 netloc = urlparse(url).netloc402396 397 if no_proxy:398 # We need to check whether we match here. We need to see if we match399 # the end of the netloc, both with and without the port.400 no_proxy = no_proxy.split(',')407 netloc = urlparse(url).netloc408401 402 for host in no_proxy:403 if netloc.endswith(host) or netloc.split(':')[0].endswith(host):404 # The URL does match something in no_proxy, so we don't want405 # to apply the proxies on this URL.406 return {}407 408 # If the system proxy settings indicate that this URL should be bypassed,409 # don't proxy.410 if proxy_bypass(netloc):411 return {}412413 # If we get here, we either didn't have no_proxy set or we're not going416 # anywhere that no_proxy applies to.417 proxies = [(key, get_proxy(key + '_proxy')) for key in proxy_keys]418 return dict([(key, val) for (key, val) in proxies if val])414 # anywhere that no_proxy applies to, and the system settings don't require415 # bypassing the proxy for the current URL.416 return getproxies()417 418420419def default_user_agent():420 """Return a string representing the default user agent."""421 _implementation = platform.python_implementation()422
126 unmodified lines
modified:AUTHORS.rst+4 added
123 unmodified lines
124- Wilfred Hughes <me@wilfred.me.uk> @dontYetKnow125- Dmitry Medvinsky <me@dmedvinsky.name>126- Bryce Boe <bbzbryce@gmail.com> @bboe127- Colin Dunklau <colin.dunklau@gmail.com> @cdunklau128- Bob Carroll <bob.carroll@alum.rit.edu> @rcarz129- Hugo Osvaldo Barrera <hugo@osvaldobarrera.com.ar> @hobarrera130- Łukasz Langa <lukasz@langa.pl> @llanga131- Dave Shawley <daveshawley@gmail.com>132- James Clarke (jam)133- Kevin Burke <kev@inburke.com>134- Flavio Curella
deleted:invokefile.py-5 removed
1from invoke import run, task23@task4def build():5 print("Building!")
modified:test_requests.py+76 added-1 removed
85 unmodified lines
86 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()87 self.assertEqual(request.url,88 "http://example.com/path?key=value&a=b#fragment")8990 def test_mixed_case_scheme_acceptable(self):91 s = requests.Session()92 r = requests.Request('GET', 'http://httpbin.org/get')93 r = s.send(r.prepare())94 self.assertEqual(r.status_code,200)95 s = requests.Session()96 r = requests.Request('GET', 'HTTP://httpbin.org/get')97 r = s.send(r.prepare())98 self.assertEqual(r.status_code,200)99 r = requests.Request('GET', 'hTTp://httpbin.org/get')100 r = s.send(r.prepare())101 self.assertEqual(r.status_code,200)102 r = requests.Request('GET', 'HttP://httpbin.org/get')103 r = s.send(r.prepare())104 self.assertEqual(r.status_code,200)105 r = requests.Request('GET', 'https://httpbin.org/get')106 r = s.send(r.prepare())107 self.assertEqual(r.status_code,200)108 r = requests.Request('GET', 'HTTPS://httpbin.org/get')109 r = s.send(r.prepare())110 self.assertEqual(r.status_code,200)111 r = requests.Request('GET', 'hTTps://httpbin.org/get')112 r = s.send(r.prepare())113 self.assertEqual(r.status_code,200)114 r = requests.Request('GET', 'HttPs://httpbin.org/get')115 r = s.send(r.prepare())116 self.assertEqual(r.status_code,200)117118 def test_HTTP_200_OK_GET_ALTERNATIVE(self):119 r = requests.Request('GET', httpbin('get'))120 s = requests.Session()121
47 unmodified lines
169 }170 )171 assert 'foo' not in s.cookies172173 def test_cookie_quote_wrapped(self):174 s = requests.session()175 s.get(httpbin('cookies/set?foo="bar:baz"'))176 self.assertTrue(s.cookies['foo'] == '"bar:baz"')177178 def test_request_cookie_overrides_session_cookie(self):179 s = requests.session()180 s.cookies['foo'] = 'bar'181 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})
10 unmodified lines
192 # Make sure the cookie was sent193 assert r.json()['cookies']['foo'] == 'bar'194 # Make sure the session cj is still the custom one195 assert s.cookies is cj163196 197 def test_requests_in_history_are_not_overridden(self):198 resp = requests.get(httpbin('redirect/3'))199 urls = [r.url for r in resp.history]200 req_urls = [r.request.url for r in resp.history]201 self.assertEquals(urls, req_urls)202 203 def test_user_agent_transfers(self):204205 heads = {206 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'
31 unmodified lines
238 s.auth = auth239 r = s.get(url)240 self.assertEqual(r.status_code, 200)241242 def test_basicauth_with_netrc(self):243 auth = ('user', 'pass')244 wrong_auth = ('wronguser', 'wrongpass')245 url = httpbin('basic-auth', 'user', 'pass')246247 def get_netrc_auth_mock(url):248 return auth249 requests.sessions.get_netrc_auth = get_netrc_auth_mock250251 # Should use netrc and work.252 r = requests.get(url)253 self.assertEqual(r.status_code, 200)254255 # Given auth should override and fail.256 r = requests.get(url, auth=wrong_auth)257 self.assertEqual(r.status_code, 401)258259 s = requests.session()260 261 # Should use netrc and work.262 r = s.get(url)263 self.assertEqual(r.status_code, 200)264265 # Given auth should override and fail.266 s.auth = wrong_auth267 r = s.get(url)268 self.assertEqual(r.status_code, 401)269270 def test_DIGEST_HTTP_200_OK_GET(self):271272 auth = HTTPDigestAuth('user', 'pass')273 url = httpbin('digest-auth', 'auth', 'user', 'pass')
288 unmodified lines
562 headers['ACCEPT'.encode('ascii')],563 'application/json'564 )565566 def test_uppercase_scheme(self):567 r = requests.get('HTTP://example.com/')568 self.assertEqual(r.status_code, 200)569570 def test_uppercase_scheme_redirect(self):571 r = requests.get(httpbin('redirect-to'), params={'url': 'HTTP://example.com/'})572 self.assertEqual(r.status_code, 200)573574 def test_transport_adapter_ordering(self):575 s = requests.Session()576 order = ['https://', 'http://']577 self.assertEqual(order, list(s.adapters))
204 unmodified lines