Skip to content
Myr

urllib3 upgrade

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 · parent 85507dd · Browse files · 7 files+357 added−144 removed
This commit

State

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

Diff stats

7 files+357 added−144 removed

  • other:+357 added−144 removed

7 files+357 added−144 removed

modified:requests/packages/urllib3/__init__.py+20 added-4 removed
6 unmodified lines
7"""8urllib3 - Thread-safe connection pooling and re-using.9"""1011__author__ = "Andrey Petrov (andrey.petrov@shazow.net)"12__license__ = "MIT"13__version__ = "$Rev$"11__author__ = 'Andrey Petrov (andrey.petrov@shazow.net)'12__license__ = 'MIT'13__version__ = '1.0'141516from .connectionpool import (17 HTTPConnectionPool,
8 unmodified lines
26 MaxRetryError,27 SSLError,28 TimeoutError)2930from .poolmanager import PoolManager30from .poolmanager import PoolManager, ProxyManager, proxy_from_url31from .response import HTTPResponse32from .filepost import encode_multipart_formdata333435# Set default logging handler to avoid "No handler found" warnings.36import logging37try:38 from logging import NullHandler39except ImportError:40 class NullHandler(logging.Handler):41 def emit(self, record):42 pass4344logging.getLogger(__name__).addHandler(NullHandler())4546# ... Clean up.47del logging48del NullHandler
modified:requests/packages/urllib3/_collections.py+1 added-2 removed
103 unmodified lines
104105 # Discard invalid and excess entries106 self._prune_entries(len(self._container) - self._maxsize)107108108 def __delitem__(self, key):109 self._invalidate_entry(key)110 del self._container[key]111 del self._access_lookup[key]112113 def __len__(self):115 return len(self.access_log)114 return self._container.__len__()115116 def __iter__(self):117 return self._container.__iter__()118
2 unmodified lines
modified:requests/packages/urllib3/connectionpool.py+106 added-114 removed
6 unmodified lines
7import logging8import socket91011from urllib import urlencode11from httplib import HTTPConnection, HTTPSConnection, HTTPException12from Queue import Queue, Empty, Full13from select import select14from socket import error as SocketError, timeout as SocketTimeout
6 unmodified lines
21 ssl = None22 BaseSSLError = None232426from .filepost import encode_multipart_formdata25from .request import RequestMethods26from .response import HTTPResponse27from .exceptions import (28 SSLError,29 MaxRetryError,30 TimeoutError,31 HostChangedError,33 EmptyPoolError)32 EmptyPoolError,33)343536log = logging.getLogger(__name__)3738_Default = object()39404141## Connection objects (extension of httplib)4243class VerifiedHTTPSConnection(HTTPSConnection):44 """45 Based on httplib.HTTPSConnection but wraps the socket with46 SSL certification.47 """48 cert_reqs = None49 cert_reqs = None5050 def __init__(self, **kwargs):51 HTTPSConnection.__init__(self, **kwargs)52 self.cert_reqs = None53 self.ca_certs = None5451 def set_cert(self, key_file=None, cert_file=None,52 cert_reqs='CERT_NONE', ca_certs=None):53 ssl_req_scheme = {54 'CERT_NONE': ssl.CERT_NONE,
19 unmodified lines
7475## Pool objects7677class ConnectionPool(object):78 """79 Base class for all connection pools, such as80 :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.81 """82 pass838485class HTTPConnectionPool(ConnectionPool):85class HTTPConnectionPool(ConnectionPool, RequestMethods):86 """87 Thread-safe connection pool for one host.8889 host89 :param host:90 Host used for this HTTP Connection (e.g. "localhost"), passed into91 httplib.HTTPConnection()91 :class:`httplib.HTTPConnection`.9293 port93 :param port:94 Port used for this HTTP Connection (None is equivalent to 80), passed95 into httplib.HTTPConnection()95 into :class:`httplib.HTTPConnection`.9697 strict97 :param strict:98 Causes BadStatusLine to be raised if the status line can't be parsed99 as a valid HTTP/1.0 or 1.1 status line, passed into100 httplib.HTTPConnection()100 :class:`httplib.HTTPConnection`.101102 timeout102 :param timeout:103 Socket timeout for each individual connection, can be a float. None104 disables timeout.105106 maxsize106 :param maxsize:107 Number of connections to save that can be reused. More than 1 is useful108 in multithreaded situations. If ``block`` is set to false, more109 connections will be created but they will not be saved once they've110 been used.111112 block112 :param block:113 If set to True, no more than ``maxsize`` connections will be used at114 a time. When no free connections are available, the call will block115 until a connection has been released. This is a useful side effect for116 particular multithreaded situations where one does not want to use more117 than maxsize connections per host to prevent flooding.118119 headers119 :param headers:120 Headers to include with all requests, unless other headers are given121 explicitly.122 """123
18 unmodified lines
142 self.num_requests = 0143144 def _new_conn(self):145 """146 Return a fresh HTTPConnection.146 Return a fresh :class:`httplib.HTTPConnection`.147 """148 self.num_connections += 1149 log.info("Starting new HTTP connection (%d): %s" %150 (self.num_connections, self.host))
1 unmodified line
152153 def _get_conn(self, timeout=None):154 """155 Get a connection. Will return a pooled connection if one is available.156157 If no connections are available and :prop:`.block` is ``False``, then a156 Otherwise, a fresh connection is returned.158 fresh connection is returned.159160 :param timeout:161 Seconds to wait before giving up and raising162 :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and163 :prop:`.block` is ``True``.164 """165 conn = None166 try:167 conn = self.pool.get(block=self.block, timeout=timeout)
14 unmodified lines
182183 def _put_conn(self, conn):184 """185 Put a connection back into the pool.186187 :param conn:188 Connection object for the current host and port as returned by189 :meth:`._new_conn` or :meth:`._get_conn`.190191 If the pool is already full, the connection is discarded because we192 exceeded maxsize. If connections are discarded frequently, then maxsize193 should be increased.194 """
14 unmodified lines
209210 if timeout is _Default:211 timeout = self.timeout212201213 conn.request(method, url, **httplib_request_kw)214 conn.sock.settimeout(timeout)215 httplib_response = conn.getresponse()216206217 log.debug("\"%s %s %s\" %s %s" %218 (method, url,219 conn._http_vsn_str, # pylint: disable-msg=W0212220 httplib_response.status, httplib_response.length))
1 unmodified line
222 return httplib_response223224225 def is_same_host(self, url):226 """227 Check if the given ``url`` is a member of the same host as this228 conncetion pool.229 """230 # TODO: Add optional support for socket.gethostbyname checking.231 return (url.startswith('/') or232 get_host(url) == (self.scheme, self.host, self.port))233234 def urlopen(self, method, url, body=None, headers=None, retries=3,235 redirect=True, assert_same_host=True, timeout=_Default,236 pool_timeout=None, release_conn=None, **response_kw):237 """223 Get a connection from the pool and perform an HTTP request.238 Get a connection from the pool and perform an HTTP request. This is the239 lowest level call for making a request, so you'll need to specify all240 the raw details.241225 method242 .. note::243244 More commonly, it's appropriate to use a convenience method provided245 by :class:`.RequestMethods`, such as :meth:`.request`.246247 :param method:248 HTTP request method (such as GET, POST, PUT, etc.)249228 body250 :param body:251 Data to send in the request body (useful for creating252 POST requests, see HTTPConnectionPool.post_url for253 more convenience).254233 headers255 :param headers:256 Dictionary of custom headers to send, such as User-Agent,257 If-None-Match, etc. If None, pool headers are used. If provided,258 these headers completely replace any pool-specific headers.259238 retries260 :param retries:261 Number of retries to allow before raising262 a MaxRetryError exception.263242 redirect264 :param redirect:265 Automatically handle redirects (status codes 301, 302, 303, 307),266 each redirect counts as a retry.267246 assert_same_host247 If True, will make sure that the host of the pool requests is268 :param assert_same_host:269 If ``True``, will make sure that the host of the pool requests is270 consistent else will raise HostChangedError. When False, you can271 use the pool on an HTTP proxy and request foreign hosts.272251 timeout273 :param timeout:274 If specified, overrides the default timeout for this one request.275254 pool_timeout276 :param pool_timeout:277 If set and the pool is set to block=True, then this method will278 block for ``pool_timeout`` seconds and raise EmptyPoolError if no279 connection is available within the time period.280259 release_conn281 :param release_conn:282 If False, then the urlopen call will not release the connection283 back into the pool once a response is received. This is useful if284 you're not preloading the response's content immediately. You will285 need to call ``r.release_conn()`` on the response ``r`` to return286 the connection back into the pool. If None, it takes the value of287 ``response_kw.get('preload_content', True)``.288289 :param \**response_kw:267 Additional parameters are passed to268 ``HTTPResponse.from_httplib(r, **response_kw)``290 Additional parameters are passed to291 :meth:`urllib3.response.HTTPResponse.from_httplib`292 """293 if headers is None:294 headers = self.headers295
17 unmodified lines
313 try:314 # Request a connection from the queue315 # (Could raise SocketError: Bad file descriptor)316 conn = self._get_conn(timeout=pool_timeout)317318 # Make the request on the httplib connection object319 httplib_response = self._make_request(conn, method, url,320 timeout=timeout,321 body=body, headers=headers)298 # print '!'322323 # Import httplib's response into our own wrapper object324 response = HTTPResponse.from_httplib(httplib_response,325 pool=self,
44 unmodified lines
370 assert_same_host)371372 return response373351 def get_url(self, url, fields=None, headers=None, retries=3,352 redirect=True, **response_kw):353 """354 Wrapper for performing GET with urlopen (see urlopen for more details).374356 Supports an optional ``fields`` dictionary parameter key/value strings.357 If provided, they will be added to the url.358 """359 if fields:360 url += '?' + urlencode(fields)361 return self.urlopen('GET', url, headers=headers, retries=retries,362 redirect=redirect, **response_kw)375class HTTPSConnectionPool(HTTPConnectionPool):376 """377 Same as :class:`.HTTPConnectionPool`, but HTTPS.378364 def post_url(self, url, fields=None, headers=None, retries=3,365 redirect=True, encode_multipart=True, multipart_boundary=None,366 **response_kw):367 """368 Wrapper for performing POST with urlopen (see urlopen369 for more details).379 When Python is compiled with the :mod:`ssl` module, then380 :class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,381 instead of :class:httplib.HTTPSConnection`.382371 Supports an optional ``fields`` parameter of key/value strings AND372 key/filetuple. A filetuple is a (filename, data) tuple. For example:373374 fields = {375 'foo': 'bar',376 'foofile': ('foofile.txt', 'contents of foofile'),377 }378379 If encode_multipart=True (default), then380 ``urllib3.filepost.encode_multipart_formdata`` is used to encode the381 payload with the appropriate content type. Otherwise382 ``urllib.urlencode`` is used with 'application/x-www-form-urlencoded'383 content type.384385 Multipart encoding must be used when posting files, and it's reasonably386 safe to use it other times too. It may break request signing, such as387 OAuth.388389 NOTE: If ``headers`` are supplied, the 'Content-Type' value will be390 overwritten because it depends on the dynamic random boundary string391 which is used to compose the body of the request.392 """393 if encode_multipart:394 body, content_type = encode_multipart_formdata(fields or {},395 boundary=multipart_boundary)396 else:397 body, content_type = (398 urlencode(fields or {}),399 'application/x-www-form-urlencoded')400401 headers = headers or {}402 headers.update({'Content-Type': content_type})403404 return self.urlopen('POST', url, body, headers=headers,405 retries=retries, redirect=redirect, **response_kw)406407408class HTTPSConnectionPool(HTTPConnectionPool):383 The ``key_file``, ``cert_file``, ``cert_reqs``, and ``ca_certs`` parameters384 are only used if :mod:`ssl` is available and are fed into385 :meth:`ssl.wrap_socket` to upgrade the connection socket into an SSL socket.386 """410 Same as HTTPConnectionPool, but HTTPS.411 """387388 scheme = 'https'389390 def __init__(self, host, port=None,391 strict=False, timeout=None, maxsize=1,392 block=False, headers=None,393 key_file=None, cert_file=None,419 cert_reqs=ssl.CERT_REQUIRED, ca_certs=None):394 cert_reqs='CERT_NONE', ca_certs=None):395396 super(HTTPSConnectionPool, self).__init__(host, port,397 strict, timeout, maxsize,398 block, headers)
3 unmodified lines
402 self.ca_certs = ca_certs403404 def _new_conn(self):405 """431 Return a fresh HTTPSConnection.406 Return a fresh :class:`httplib.HTTPSConnection`.407 """433408 self.num_connections += 1409 log.info("Starting new HTTPS connection (%d): %s"410 % (self.num_connections, self.host))411
12 unmodified lines
424 basic_auth=None):425 """426 Shortcuts for generating request headers.427454 keep_alive455 If true, adds 'connection: keep-alive' header.428 :param keep_alive:429 If ``True``, adds 'connection: keep-alive' header.430457 accept_encoding431 :param accept_encoding:432 Can be a boolean, list, or string.459 True translates to 'gzip,deflate'.433 ``True`` translates to 'gzip,deflate'.434 List will get joined by comma.435 String will be used as provided.436463 user_agent437 :param user_agent:438 String representing the user-agent you want, such as439 "python-urllib3/0.6"440467 basic_auth441 :param basic_auth:442 Colon-separated username:password string for 'authorization: basic ...'443 auth header.444445 Example: ::446447 >>> make_headers(keep_alive=True, user_agent="Batman/1.0")448 {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}449 >>> make_headers(accept_encoding=True)450 {'accept-encoding': 'gzip,deflate'}451 """452 headers = {}453 if accept_encoding:454 if isinstance(accept_encoding, str):
20 unmodified lines
475def get_host(url):476 """477 Given a url, return its scheme, host and port (None if it's not there).478498 For example:499 >>> get_host('http://google.com/mail/')500 http, google.com, None501 >>> get_host('google.com:80')502 http, google.com, 80479 For example: ::480481 >>> get_host('http://google.com/mail/')482 ('http', 'google.com', None)483 >>> get_host('google.com:80')484 ('http', 'google.com', 80)485 """486 # This code is actually similar to urlparse.urlsplit, but much487 # simplified for our needs.488 port = None
9 unmodified lines
498499500def connection_from_url(url, **kw):501 """520 Given a url, return an HTTP(S)ConnectionPool instance of its host.502 Given a url, return an :class:`.ConnectionPool` instance of its host.503522 This is a shortcut for not having to determine the host of the url523 before creating an HTTP(S)ConnectionPool instance.504 This is a shortcut for not having to parse out the scheme, host, and port505 of the url before creating an :class:`.ConnectionPool` instance.506525 Passes on whatever kw arguments to the constructor of526 HTTP(S)ConnectionPool. (e.g. timeout, maxsize, block)507 :param url:508 Absolute URL string that must include the scheme. Port is optional.509510 :param \**kw:511 Passes additional parameters to the constructor of the appropriate512 :class:`.ConnectionPool`. Useful for specifying things like513 timeout, maxsize, headers, etc.514515 Example: ::516517 >>> conn = connection_from_url('http://google.com/')518 >>> r = conn.request('GET', '/')519 """520 scheme, host, port = get_host(url)521 if scheme == 'https':522 return HTTPSConnectionPool(host, port=port, **kw)
2 unmodified lines
modified:requests/packages/urllib3/filepost.py+13 added
20 unmodified lines
21 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'222324def encode_multipart_formdata(fields, boundary=None):25 """26 Encode a dictionary of ``fields`` using the multipart/form-data mime format.2728 :param fields:29 Dictionary of fields. The key is treated as the field name, and the30 value as the body of the form-data. If the value is a tuple of two31 elements, then the first element is treated as the filename of the32 form-data section.3334 :param boundary:35 If not specified, then a random boundary will be generated using36 :func:`mimetools.choose_boundary`.37 """38 body = StringIO()39 if boundary is None:40 boundary = mimetools.choose_boundary()41
30 unmodified lines
modified:requests/packages/urllib3/poolmanager.py+62 added-15 removed
3 unmodified lines
4# This module is part of urllib3 and is released under5# the MIT License: http://www.opensource.org/licenses/mit-license.php67from ._collections import RecentlyUsedContainer8from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, get_host8from .connectionpool import (9 HTTPConnectionPool, HTTPSConnectionPool,10 get_host, connection_from_url,11)121314__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']151617from .request import RequestMethods18from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool192021pool_classes_by_scheme = {22 'http': HTTPConnectionPool,23 'https': HTTPSConnectionPool,24}
3 unmodified lines
28 'https': 443,29}303122class PoolManager(object):32class PoolManager(RequestMethods):33 """34 Allows for arbitrary requests while transparently keeping track of35 necessary connection pools for you.3627 num_pools37 :param num_pools:38 Number of connection pools to cache before discarding the least recently39 used pool.4041 :param \**connection_pool_kw:31 Additional parameters are used to create fresh ConnectionPool instances.42 Additional parameters are used to create fresh43 :class:`urllib3.connectionpool.ConnectionPool` instances.4445 Example: ::4647 >>> manager = PoolManager()48 >>> r = manager.urlopen("http://google.com/")49 >>> r = manager.urlopen("http://google.com/mail")50 >>> r = manager.urlopen("http://yahoo.com/")51 >>> len(r.pools)52 25354 """5556 # TODO: Make sure there are no memory leaks here.5758 def __init__(self, num_pools=10, **connection_pool_kw):59 self.connection_pool_kw = connection_pool_kw3960 self.pools = RecentlyUsedContainer(num_pools)41 self.recently_used_pools = []6162 def connection_from_host(self, host, port=80, scheme='http'):63 """45 Get a ConnectionPool based on the host, port, and scheme.64 Get a :class:`ConnectionPool` based on the host, port, and scheme.6566 Note that an appropriate ``port`` value is required here to normalize67 connection pools in our container most effectively.68 """69 pool_key = (scheme, host, port)704971 # If the scheme, host, or port doesn't match existing open connections,72 # open a new ConnectionPool.73 pool = self.pools.get(pool_key)74 if pool:
8 unmodified lines
83 return pool8485 def connection_from_url(self, url):86 """66 Similar to connectionpool.connection_from_url but doesn't pass any67 additional keywords to the ConnectionPool constructor. Additional68 keywords are taken from the PoolManager constructor.87 Similar to :func:`urllib3.connectionpool.connection_from_url` but88 doesn't pass any additional parameters to the89 :class:`urllib3.connectionpool.ConnectionPool` constructor.9091 Additional parameters are taken from the :class:`.PoolManager`92 constructor.93 """94 scheme, host, port = get_host(url)9596 port = port or port_by_scheme.get(scheme, 80)9774 r = self.connection_from_host(host, port=port, scheme=scheme)98 return self.connection_from_host(host, port=port, scheme=scheme)9976 return r100 def urlopen(self, method, url, **kw):101 """102 Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.103104 ``url`` must be absolute, such that an appropriate105 :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.106 """107 conn = self.connection_from_url(url)108 return conn.urlopen(method, url, assert_same_host=False, **kw)109110111class ProxyManager(object):112 """113 Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method114 will make requests to any url through the defined proxy.115 """116117 def __init__(self, proxy_pool):118 self.proxy_pool = proxy_pool119120 def urlopen(self, method, url, **kw):121 "Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."80 conn = self.connection_from_url(url)81 return conn.urlopen(method, url, **kw)122 kw['assert_same_host'] = False123 return self.proxy_pool.urlopen(method, url, **kw)124125126def proxy_from_url(url, **pool_kw):127 proxy_pool = connection_from_url(url, **pool_kw)128 return ProxyManager(proxy_pool)
added:requests/packages/urllib3/request.py+145 added
1# urllib3/request.py2# Copyright 2008-2011 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.php678from urllib import urlencode910from .filepost import encode_multipart_formdata111213__all__ = ['RequestMethods']141516class RequestMethods(object):17 """18 Convenience mixin for classes who implement a :meth:`urlopen` method, such19 as :class:`~urllib3.connectionpool.HTTPConnectionPool` and20 :class:`~urllib3.poolmanager.PoolManager`.2122 Provides behavior for making common types of HTTP request methods and23 decides which type of request field encoding to use.2425 Specifically,2627 :meth:`.request_encode_url` is for sending requests whose fields are encoded28 in the URL (such as GET, HEAD, DELETE).2930 :meth:`.request_encode_body` is for sending requests whose fields are31 encoded in the *body* of the request using multipart or www-orm-urlencoded32 (such as for POST, PUT, PATCH).3334 :meth:`.request` is for making any kind of request, it will look up the35 appropriate encoding format and use one of the above two methods to make36 the request.37 """3839 _encode_url_methods = set(['DELETE', 'GET', 'HEAD', 'OPTIONS'])4041 _encode_body_methods = set(['PATCH', 'POST', 'PUT', 'TRACE'])4243 def urlopen(self, method, url, body=None, headers=None,44 encode_multipart=True, multipart_boundary=None,45 **kw):46 raise NotImplemented("Classes extending RequestMethods must implement "47 "their own ``urlopen`` method.")4849 def request(self, method, url, fields=None, headers=None, **urlopen_kw):50 """51 Make a request using :meth:`urlopen` with the appropriate encoding of52 ``fields`` based on the ``method`` used.5354 This is a convenience method that requires the least amount of manual55 effort. It can be used in most situations, while still having the option56 to drop down to more specific methods when necessary, such as57 :meth:`request_encode_url`, :meth:`request_encode_body`,58 or even the lowest level :meth:`urlopen`.59 """60 method = method.upper()6162 if method in self._encode_url_methods:63 return self.request_encode_url(method, url, fields=fields,64 headers=headers,65 **urlopen_kw)66 else:67 return self.request_encode_body(method, url, fields=fields,68 headers=headers,69 **urlopen_kw)7071 def request_encode_url(self, method, url, fields=None, **urlopen_kw):72 """73 Make a request using :meth:`urlopen` with the ``fields`` encoded in74 the url. This is useful for request methods like GET, HEAD, DELETE, etc.75 """76 if fields:77 url += '?' + urlencode(fields)78 return self.urlopen(method, url, **urlopen_kw)7980 def request_encode_body(self, method, url, fields=None, headers=None,81 encode_multipart=True, multipart_boundary=None,82 **urlopen_kw):83 """84 Make a request using :meth:`urlopen` with the ``fields`` encoded in85 the body. This is useful for request methods like POST, PUT, PATCH, etc.8687 When ``encode_multipart=True`` (default), then88 :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the89 payload with the appropriate content type. Otherwise90 :meth:`urllib.urlencode` is used with the91 'application/x-www-form-urlencoded' content type.9293 Multipart encoding must be used when posting files, and it's reasonably94 safe to use it in other times too. However, it may break request signing,95 such as with OAuth.9697 Supports an optional ``fields`` parameter of key/value strings AND98 key/filetuple. A filetuple is a (filename, data) tuple. For example: ::99100 fields = {101 'foo': 'bar',102 'fakefile': ('foofile.txt', 'contents of foofile'),103 'realfile': ('barfile.txt', open('realfile').read()),104 'nonamefile': ('contents of nonamefile field'),105 }106107 When uploading a file, providing a filename (the first parameter of the108 tuple) is optional but recommended to best mimick behavior of browsers.109110 Note that if ``headers`` are supplied, the 'Content-Type' header will be111 overwritten because it depends on the dynamic random boundary string112 which is used to compose the body of the request. The random boundary113 string can be explicitly set with the ``multipart_boundary`` parameter.114 """115 if encode_multipart:116 body, content_type = encode_multipart_formdata(fields or {},117 boundary=multipart_boundary)118 else:119 body, content_type = (urlencode(fields or {}),120 'application/x-www-form-urlencoded')121122 headers = headers or {}123 headers.update({'Content-Type': content_type})124125 return self.urlopen(method, url, body=body, headers=headers,126 **urlopen_kw)127128 # Deprecated:129130 def get_url(self, url, fields=None, **urlopen_kw):131 """132 .. deprecated:: 1.0133 Use :meth:`request` instead.134 """135 return self.request_encode_url('GET', url, fields=fields,136 **urlopen_kw)137138 def post_url(self, url, fields=None, headers=None, **urlopen_kw):139 """140 .. deprecated:: 1.0141 Use :meth:`request` instead.142 """143 return self.request_encode_body('POST', url, fields=fields,144 headers=headers,145 **urlopen_kw)
modified:requests/packages/urllib3/response.py+10 added-9 removed
40 unmodified lines
41 loaded and decoded on-demand when the ``data`` property is accessed.4243 Extra parameters for behaviour not present in httplib.HTTPResponse:4445 preload_content45 :param preload_content:46 If True, the response's body will be preloaded during construction.4748 decode_content48 :param decode_content:49 If True, attempts to decode specific content-encoding's based on headers50 (like 'gzip' and 'deflate') will be skipped and raw data will be used51 instead.5253 original_response53 :param original_response:54 When this HTTPResponse wrapper is generated from an httplib.HTTPResponse55 object, it's convenient to include the original for debug purposes. It's56 otherwise unused.57 """
44 unmodified lines
102 cache_content=True)103104 def read(self, amt=None, decode_content=True, cache_content=False):105 """106 Similar to ``httplib.HTTPResponse.read(amt=None)``.106 Similar to :meth:`httplib.HTTPResponse.read`, but with two additional107 parameters: ``decode_content`` and ``cache_content``.108108 amt109 :param amt:110 How much of the content to read. If specified, decoding and caching111 is skipped because we can't decode partial content nor does it make112 sense to cache partial content as the full response.113113 decode_content114 :param decode_content:115 If True, will attempt to decode the body based on the116 'content-encoding' header. (Overridden if ``amt`` is set.)117117 cache_content118 :param cache_content:119 If True, will save the returned data such that the same result is120 returned despite of the state of the underlying file object. This121 is useful if you want the ``.data`` property to continue working122 after having ``.read()`` the file object. (Overridden if ``amt`` is
33 unmodified lines
156157 @staticmethod158 def from_httplib(r, **response_kw):159 """159 Given an httplib.HTTPResponse instance ``r``, return a corresponding160 urllib3.HTTPResponse object.160 Given an :class:`httplib.HTTPResponse` instance ``r``, return a161 corresponding :class:`urllib3.response.HTTPResponse` object.162163 Remaining parameters are passed to the HTTPResponse constructor, along164 with ``original_response=r``.165 """
16 unmodified lines