urllib update and junks
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 0d9ab27 · Browse files · 7 files·+322 added−214 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+322 added−214 removed
- other:+322 added−214 removed
Provenance
- Commit
e02fb2e- Tree
401e8e3- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
0d9ab27
7 files changed+322 added−214 removed
modified:requests/packages/urllib3/_collections.py+64 added-101 removed
2 unmodified lines3 #4 # This module is part of urllib3 and is released under5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7-from collections import deque7+from collections import MutableMapping8+from threading import Lock9 9-from threading import RLock10+try: # Python 2.7+11+ from collections import OrderedDict12+except ImportError:13+ from .packages.ordered_dict import OrderedDict14 15+16 __all__ = ['RecentlyUsedContainer']17 18 14-class AccessEntry(object):15- __slots__ = ('key', 'is_valid')19+_Null = object()20 17- def __init__(self, key, is_valid=True):18- self.key = key19- self.is_valid = is_valid21 22+class RecentlyUsedContainer(MutableMapping):23+ """24+ Provides a thread-safe dict-like container which maintains up to25+ ``maxsize`` keys while throwing away the least-recently-used keys beyond26+ ``maxsize``.27 22-class RecentlyUsedContainer(dict):28+ :param maxsize:29+ Maximum number of recent elements to retain.30+31+ :param dispose_func:32+ Every time an item is evicted from the container,33+ ``dispose_func(value)`` is called. Callback which will get called34 """24- Provides a dict-like that maintains up to ``maxsize`` keys while throwing25- away the least-recently-used keys beyond ``maxsize``.26- """35 28- # If len(self.access_log) exceeds self._maxsize * CLEANUP_FACTOR, then we29- # will attempt to cleanup the invalidated entries in the access_log30- # datastructure during the next 'get' operation.31- CLEANUP_FACTOR = 1036+ ContainerCls = OrderedDict37 33- def __init__(self, maxsize=10):38+ def __init__(self, maxsize=10, dispose_func=None):39 self._maxsize = maxsize40+ self.dispose_func = dispose_func41 36- self._container = {}42+ self._container = self.ContainerCls()43+ self._lock = Lock()44 38- # We use a deque to to store our keys ordered by the last access.39- self.access_log = deque()40- self.access_log_lock = RLock()45+ def __getitem__(self, key):46+ # Re-insert the item, moving it to the end of the eviction line.47+ with self._lock:48+ item = self._container.pop(key)49+ self._container[key] = item50+ return item51 42- # We look up the access log entry by the key to invalidate it so we can43- # insert a new authorative entry at the head without having to dig and44- # find the old entry for removal immediately.45- self.access_lookup = {}52+ def __setitem__(self, key, value):53+ evicted_value = _Null54+ with self._lock:55+ # Possibly evict the existing value of 'key'56+ evicted_value = self._container.get(key, _Null)57+ self._container[key] = value58 47- # Trigger a heap cleanup when we get past this size48- self.access_log_limit = maxsize * self.CLEANUP_FACTOR59+ # If we didn't evict an existing value, we might have to evict the60+ # least recently used item from the beginning of the container.61+ if len(self._container) > self._maxsize:62+ _key, evicted_value = self._container.popitem(last=False)63 50- def _invalidate_entry(self, key):51- "If exists: Invalidate old entry and return it."52- old_entry = self.access_lookup.get(key)53- if old_entry:54- old_entry.is_valid = False64+ if self.dispose_func and evicted_value is not _Null:65+ self.dispose_func(evicted_value)66 56- return old_entry67+ def __delitem__(self, key):68+ with self._lock:69+ value = self._container.pop(key)70 58- def _push_entry(self, key):59- "Push entry onto our access log, invalidate the old entry if exists."60- self._invalidate_entry(key)71+ if self.dispose_func:72+ self.dispose_func(value)73 62- new_entry = AccessEntry(key)63- self.access_lookup[key] = new_entry74+ def __len__(self):75+ with self._lock:76+ return len(self._container)77 65- self.access_log_lock.acquire()66- self.access_log.appendleft(new_entry)67- self.access_log_lock.release()78+ def __iter__(self):79+ raise NotImplementedError('Iteration over this class is unlikely to be threadsafe.')80 69- def _prune_entries(self, num):70- "Pop entries from our access log until we popped ``num`` valid ones."71- while num > 0:72- self.access_log_lock.acquire()73- p = self.access_log.pop()74- self.access_log_lock.release()81+ def clear(self):82+ with self._lock:83+ # Copy pointers to all values, then wipe the mapping84+ # under Python 2, this copies the list of values twice :-|85+ values = list(self._container.values())86+ self._container.clear()87 76- if not p.is_valid:77- continue # Invalidated entry, skip88+ if self.dispose_func:89+ for value in values:90+ self.dispose_func(value)91 79- dict.pop(self, p.key, None)80- self.access_lookup.pop(p.key, None)81- num -= 182-83- def _prune_invalidated_entries(self):84- "Rebuild our access_log without the invalidated entries."85- self.access_log_lock.acquire()86- self.access_log = deque(e for e in self.access_log if e.is_valid)87- self.access_log_lock.release()88-89- def _get_ordered_access_keys(self):90- "Return ordered access keys for inspection. Used for testing."91- self.access_log_lock.acquire()92- r = [e.key for e in self.access_log if e.is_valid]93- self.access_log_lock.release()94-95- return r96-97- def __getitem__(self, key):98- item = dict.get(self, key)99-100- if not item:101- raise KeyError(key)102-103- # Insert new entry with new high priority, also implicitly invalidates104- # the old entry.105- self._push_entry(key)106-107- if len(self.access_log) > self.access_log_limit:108- # Heap is getting too big, try to clean up any tailing invalidated109- # entries.110- self._prune_invalidated_entries()111-112- return item113-114- def __setitem__(self, key, item):115- # Add item to our container and access log116- dict.__setitem__(self, key, item)117- self._push_entry(key)118-119- # Discard invalid and excess entries120- self._prune_entries(len(self) - self._maxsize)121-122- def __delitem__(self, key):123- self._invalidate_entry(key)124- self.access_lookup.pop(key, None)125- dict.__delitem__(self, key)126-127- def get(self, key, default=None):128- try:129- return self[key]130- except KeyError:131- return default92+ def keys(self):93+ with self._lock:94+ return self._container.keys()modified:requests/packages/urllib3/connectionpool.py+59 added-22 removed
5 unmodified lines6 7 import logging8 import socket9 10-from socket import error as SocketError, timeout as SocketTimeout10+from socket import timeout as SocketTimeout11 12-try: # Python 312+try: # Python 313 from http.client import HTTPConnection, HTTPException14 from http.client import HTTP_PORT, HTTPS_PORT15 except ImportError:16 from httplib import HTTPConnection, HTTPException17 from httplib import HTTP_PORT, HTTPS_PORT18 19-try: # Python 319+try: # Python 320 from queue import LifoQueue, Empty, Full21 except ImportError:22 from Queue import LifoQueue, Empty, Full23 24 25-try: # Compiled with SSL?25+try: # Compiled with SSL?26 HTTPSConnection = object27 BaseSSLError = None28 ssl = None29 30- try: # Python 330+ try: # Python 331 from http.client import HTTPSConnection32 except ImportError:33 from httplib import HTTPSConnection34 35 import ssl36 BaseSSLError = ssl.SSLError37 38-except (ImportError, AttributeError):38+except (ImportError, AttributeError): # Platform-specific: No SSL.39 pass40 41 42 from .request import RequestMethods43 from .response import HTTPResponse44 from .util import get_host, is_connection_dropped45 from .exceptions import (46+ ClosedPoolError,47 EmptyPoolError,48 HostChangedError,49 MaxRetryError,50 SSLError,155 unmodified lines206 conn = None207 try:208 conn = self.pool.get(block=self.block, timeout=timeout)209 209- # If this is a persistent connection, check if it got disconnected210- if conn and is_connection_dropped(conn):211- log.info("Resetting dropped connection: %s" % self.host)212- conn.close()210+ except AttributeError: # self.pool is None211+ raise ClosedPoolError(self, "Pool is closed.")212 213 except Empty:214 if self.block:215 raise EmptyPoolError(self,216 "Pool reached maximum size and no more "217 "connections are allowed.")218 pass # Oh well, we'll create a new connection then219 220+ # If this is a persistent connection, check if it got disconnected221+ if conn and is_connection_dropped(conn):222+ log.info("Resetting dropped connection: %s" % self.host)223+ conn.close()224+225 return conn or self._new_conn()226 227 def _put_conn(self, conn):228 """2 unmodified lines231 :param conn:232 Connection object for the current host and port as returned by233 :meth:`._new_conn` or :meth:`._get_conn`.234 231- If the pool is already full, the connection is discarded because we232- exceeded maxsize. If connections are discarded frequently, then maxsize233- should be increased.235+ If the pool is already full, the connection is closed and discarded236+ because we exceeded maxsize. If connections are discarded frequently,237+ then maxsize should be increased.238+239+ If the pool is closed, then the connection will be closed and discarded.240 """241 try:242 self.pool.put(conn, block=False)243+ return # Everything is dandy, done.244+ except AttributeError:245+ # self.pool is None.246+ pass247 except Full:248 # This should never happen if self.block == True249 log.warning("HttpConnectionPool is full, discarding connection: %s"250 % self.host)251 252+ # Connection never got put back into the pool, close it.253+ conn.close()254+255 def _make_request(self, conn, method, url, timeout=_Default,256 **httplib_request_kw):257 """258 Perform a request on a given httplib connection object taken from our21 unmodified lines280 http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')281 log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,282 httplib_response.status,283 httplib_response.length))271-284 return httplib_response285 286+ def close(self):287+ """288+ Close all pooled connections and disable the pool.289+ """290+ # Disable access to the pool291+ old_pool, self.pool = self.pool, None292 293+ try:294+ while True:295+ conn = old_pool.get(block=False)296+ if conn:297+ conn.close()298+299+ except Empty:300+ pass # Done.301+302 def is_same_host(self, url):303 """304 Check if the given ``url`` is a member of the same host as this305 connection pool.306 """307+ if url.startswith('/'):308+ return True309+310 # TODO: Add optional support for socket.gethostbyname checking.311 scheme, host, port = get_host(url)312 313 if self.port and not port:314 # Use explicit default port for comparison when none is given.315 port = port_by_scheme.get(scheme)316 287- return (url.startswith('/') or288- (scheme, host, port) == (self.scheme, self.host, self.port))317+ return (scheme, host, port) == (self.scheme, self.host, self.port)318 319 def urlopen(self, method, url, body=None, headers=None, retries=3,320 redirect=True, assert_same_host=True, timeout=_Default,321 pool_timeout=None, release_conn=None, **response_kw):84 unmodified lines406 conn = None407 408 try:409 # Request a connection from the queue381- # (Could raise SocketError: Bad file descriptor)410 conn = self._get_conn(timeout=pool_timeout)411 412 # Make the request on the httplib connection object413 httplib_response = self._make_request(conn, method, url,34 unmodified lines448 except CertificateError as e:449 # Name mismatch450 raise SSLError(e)451 424- except (HTTPException, SocketError) as e:452+ except HTTPException as e:453 # Connection broken, discard. It will be replaced next _get_conn().454 conn = None455 # This is necessary so we can access e below456 err = e457 458 finally:431- if conn and release_conn:432- # Put the connection back to be reused459+ if release_conn:460+ # Put the connection back to be reused. If the connection is461+ # expired then it will be None, which will get replaced with a462+ # fresh connection during _get_conn.463 self._put_conn(conn)464 465 if not conn:466+ # Try again467 log.warn("Retrying (%d attempts remain) after connection "468 "broken by '%r': %s" % (retries, err, url))469 return self.urlopen(method, url, body, headers, retries - 1,439- redirect, assert_same_host) # Try again470+ redirect, assert_same_host,471+ timeout=timeout, pool_timeout=pool_timeout,472+ release_conn=release_conn, **response_kw)473 474 # Handle redirect?475 redirect_location = redirect and response.get_redirect_location()476 if redirect_location:477+ if response.status == 303:478+ method = 'GET'479 log.info("Redirecting %s -> %s" % (url, redirect_location))480 return self.urlopen(method, redirect_location, body, headers,446- retries - 1, redirect, assert_same_host)481+ retries - 1, redirect, assert_same_host,482+ timeout=timeout, pool_timeout=pool_timeout,483+ release_conn=release_conn, **response_kw)484 485 return response486 487 75 unmodified linesmodified:requests/packages/urllib3/exceptions.py+10 added
22 unmodified lines23 "Raised when SSL certificate fails in an HTTPS connection."24 pass25 26 27+class DecodeError(HTTPError):28+ "Raised when automatic decoding based on Content-Type fails."29+ pass30+31+32 ## Leaf Exceptions33 34 class MaxRetryError(PoolError):35 "Raised when the maximum number of retries is exceeded."25 unmodified lines61 "Raised when a pool runs out of connections and no more are allowed."62 pass63 64 65+class ClosedPoolError(PoolError):66+ "Raised when a request enters a pool after the pool has been closed."67+ pass68+69+70 class LocationParseError(ValueError, HTTPError):71 "Raised when get_host or similar fails to parse the URL input."72 73 def __init__(self, location):4 unmodified linesmodified:requests/packages/urllib3/poolmanager.py+42 added-22 removed
6 unmodified lines7 import logging8 9 from ._collections import RecentlyUsedContainer10 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool11-from .connectionpool import get_host, connection_from_url, port_by_scheme12-from .exceptions import HostChangedError11+from .connectionpool import connection_from_url, port_by_scheme12 from .request import RequestMethods13+from .util import parse_url14 15 16 __all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']17 29 unmodified lines47 248 49 """50 51- # TODO: Make sure there are no memory leaks here.52-51 def __init__(self, num_pools=10, **connection_pool_kw):52 self.connection_pool_kw = connection_pool_kw55- self.pools = RecentlyUsedContainer(num_pools)53+ self.pools = RecentlyUsedContainer(num_pools,54+ dispose_func=lambda p: p.close())55 57- def connection_from_host(self, host, port=80, scheme='http'):56+ def clear(self):57 """58+ Empty our store of pools and direct them all to close.59+60+ This will not affect in-flight connections, but they will not be61+ re-used after completion.62+ """63+ self.pools.clear()64+65+ def connection_from_host(self, host, port=None, scheme='http'):66+ """67 Get a :class:`ConnectionPool` based on the host, port, and scheme.68 61- Note that an appropriate ``port`` value is required here to normalize62- connection pools in our container most effectively.69+ If ``port`` isn't given, it will be derived from the ``scheme`` using70+ ``urllib3.connectionpool.port_by_scheme``.71 """72+ port = port or port_by_scheme.get(scheme, 80)73+74 pool_key = (scheme, host, port)75 76 # If the scheme, host, or port doesn't match existing open connections,77 # open a new ConnectionPool.17 unmodified lines95 96 Additional parameters are taken from the :class:`.PoolManager`97 constructor.98 """89- scheme, host, port = get_host(url)99+ u = parse_url(url)100+ return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)101 91- port = port or port_by_scheme.get(scheme, 80)92-93- return self.connection_from_host(host, port=port, scheme=scheme)94-95- def urlopen(self, method, url, **kw):102+ def urlopen(self, method, url, redirect=True, **kw):103 """97- Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.104+ Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`105+ with custom cross-host redirect logic and only sends the request-uri106+ portion of the ``url``.107 99- ``url`` must be absolute, such that an appropriate108+ The given ``url`` parameter must be absolute, such that an appropriate109 :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.110 """102- conn = self.connection_from_url(url)103- try:104- return conn.urlopen(method, url, **kw)111+ u = parse_url(url)112+ conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)113 106- except HostChangedError as e:107- kw['retries'] = e.retries # Persist retries countdown108- return self.urlopen(method, e.url, **kw)114+ kw['assert_same_host'] = False115+ kw['redirect'] = False116 117+ response = conn.urlopen(method, u.request_uri, **kw)118 119+ redirect_location = redirect and response.get_redirect_location()120+ if not redirect_location:121+ return response122+123+ if response.status == 303:124+ method = 'GET'125+126+ log.info("Redirecting %s -> %s" % (url, redirect_location))127+ kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown128+ return self.urlopen(method, redirect_location, **kw)129+130+131 class ProxyManager(RequestMethods):132 """133 Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method134 will make requests to any url through the defined proxy.24 unmodified linesmodified:requests/packages/urllib3/response.py+4 added-4 removed
8 unmodified lines9 import zlib10 11 from io import BytesIO12 13-from .exceptions import HTTPError13+from .exceptions import DecodeError14 from .packages.six import string_types as basestring15 16 17 log = logging.getLogger(__name__)129 unmodified lines147 148 try:149 if decode_content and decoder:150 data = decoder(data)151- except IOError:152- raise HTTPError("Received response with content-encoding: %s, but "153- "failed to decode it." % content_encoding)151+ except (IOError, zlib.error):152+ raise DecodeError("Received response with content-encoding: %s, but "153+ "failed to decode it." % content_encoding)154 155 if cache_content:156 self._body = data157 45 unmodified linesmodified:requests/packages/urllib3/util.py+135 added-65 removed
4 unmodified lines5 # the MIT License: http://www.opensource.org/licenses/mit-license.php6 7 8 from base64 import b64encode9+from collections import namedtuple10+from socket import error as SocketError11 12 try:13 from select import poll, POLLIN14 except ImportError: # `poll` doesn't exist on OSX and other platforms6 unmodified lines21 from .packages import six22 from .exceptions import LocationParseError23 24 23-def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,24- basic_auth=None):25+class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):26 """26- Shortcuts for generating request headers.27-28- :param keep_alive:29- If ``True``, adds 'connection: keep-alive' header.30-31- :param accept_encoding:32- Can be a boolean, list, or string.33- ``True`` translates to 'gzip,deflate'.34- List will get joined by comma.35- String will be used as provided.36-37- :param user_agent:38- String representing the user-agent you want, such as39- "python-urllib3/0.6"40-41- :param basic_auth:42- Colon-separated username:password string for 'authorization: basic ...'43- auth header.44-45- Example: ::46-47- >>> make_headers(keep_alive=True, user_agent="Batman/1.0")48- {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}49- >>> make_headers(accept_encoding=True)50- {'accept-encoding': 'gzip,deflate'}27+ Datastructure for representing an HTTP URL. Used as a return value for28+ :func:`parse_url`.29 """52- headers = {}53- if accept_encoding:54- if isinstance(accept_encoding, str):55- pass56- elif isinstance(accept_encoding, list):57- accept_encoding = ','.join(accept_encoding)58- else:59- accept_encoding = 'gzip,deflate'60- headers['accept-encoding'] = accept_encoding30+ slots = ()31 62- if user_agent:63- headers['user-agent'] = user_agent32+ def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):33+ return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)34 65- if keep_alive:66- headers['connection'] = 'keep-alive'35+ @property36+ def hostname(self):37+ """For backwards-compatibility with urlparse. We're nice like that."""38+ return self.host39 68- if basic_auth:69- headers['authorization'] = 'Basic ' + \70- b64encode(six.b(basic_auth)).decode('utf-8')40+ @property41+ def request_uri(self):42+ """Absolute path including the query string."""43+ uri = self.path or '/'44 72- return headers45+ if self.query is not None:46+ uri += '?' + self.query47 48+ return uri49 50+51 def split_first(s, delims):52 """53 Given a string and an iterable of delimiters, split on the first found78- delimiter. Return two split parts.54+ delimiter. Return two split parts and the matched delimiter.55 56 If not found, then the first part is the full input string.57 58+ Example: ::59+60+ >>> split_first('foo/bar?baz', '?/=')61+ ('foo', 'bar?baz', '/')62+ >>> split_first('foo/bar?baz', '123')63+ ('foo/bar?baz', '', None)64+65 Scales linearly with number of delims. Not ideal for large number of delims.66 """67 min_idx = None68+ min_delim = None69 for d in delims:70 idx = s.find(d)71 if idx < 0:72 continue73 90- if not min_idx:74+ if min_idx is None or idx < min_idx:75 min_idx = idx92- else:93- min_idx = min(idx, min_idx)76+ min_delim = d77 95- if min_idx < 0:96- return s, ''78+ if min_idx is None or min_idx < 0:79+ return s, '', None80 98- return s[:min_idx], s[min_idx+1:]81+ return s[:min_idx], s[min_idx+1:], min_delim82 83 101-def get_host(url):84+def parse_url(url):85 """103- Given a url, return its scheme, host and port (None if it's not there).86+ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is87+ performed to parse incomplete urls. Fields not provided will be None.88 105- For example: ::89+ Partly backwards-compatible with :mod:`urlparse`.90 107- >>> get_host('http://google.com/mail/')108- ('http', 'google.com', None)109- >>> get_host('google.com:80')110- ('http', 'google.com', 80)91+ Example: ::92+93+ >>> parse_url('http://google.com/mail/')94+ Url(scheme='http', host='google.com', port=None, path='/', ...)95+ >>> prase_url('google.com:80')96+ Url(scheme=None, host='google.com', port=80, path=None, ...)97+ >>> prase_url('/foo?bar')98+ Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)99 """100 101 # While this code has overlap with stdlib's urlparse, it is much102 # simplified for our needs and less annoying.103 # Additionally, this imeplementations does silly things to be optimal104 # on CPython.105 118- scheme = 'http'106+ scheme = None107+ auth = None108 host = None109 port = None110+ path = None111+ fragment = None112+ query = None113 114 # Scheme115 if '://' in url:116 scheme, url = url.split('://', 1)117 118 # Find the earliest Authority Terminator119 # (http://tools.ietf.org/html/rfc3986#section-3.2)128- url, _path = split_first(url, ['/', '?', '#'])120+ url, path_, delim = split_first(url, ['/', '?', '#'])121 122+ if delim:123+ # Reassemble the path124+ path = delim + path_125+126 # Auth127 if '@' in url:132- _auth, url = url.split('@', 1)128+ auth, url = url.split('@', 1)129 130 # IPv6131 if url and url[0] == '[':132 host, url = url[1:].split(']', 1)9 unmodified lines142 raise LocationParseError("Failed to parse: %s" % url)143 144 port = int(port)145 150- elif not host:146+ elif not host and url:147 host = url148 153- return scheme, host, port149+ if not path:150+ return Url(scheme, auth, host, port, path, query, fragment)151 152+ # Fragment153+ if '#' in path:154+ path, fragment = path.split('#', 1)155 156+ # Query157+ if '?' in path:158+ path, query = path.split('?', 1)159+160+ return Url(scheme, auth, host, port, path, query, fragment)161+162+163+def get_host(url):164+ """165+ Deprecated. Use :func:`.parse_url` instead.166+ """167+ p = parse_url(url)168+ return p.scheme or 'http', p.hostname, p.port169+170+171+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,172+ basic_auth=None):173+ """174+ Shortcuts for generating request headers.175+176+ :param keep_alive:177+ If ``True``, adds 'connection: keep-alive' header.178+179+ :param accept_encoding:180+ Can be a boolean, list, or string.181+ ``True`` translates to 'gzip,deflate'.182+ List will get joined by comma.183+ String will be used as provided.184+185+ :param user_agent:186+ String representing the user-agent you want, such as187+ "python-urllib3/0.6"188+189+ :param basic_auth:190+ Colon-separated username:password string for 'authorization: basic ...'191+ auth header.192+193+ Example: ::194+195+ >>> make_headers(keep_alive=True, user_agent="Batman/1.0")196+ {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}197+ >>> make_headers(accept_encoding=True)198+ {'accept-encoding': 'gzip,deflate'}199+ """200+ headers = {}201+ if accept_encoding:202+ if isinstance(accept_encoding, str):203+ pass204+ elif isinstance(accept_encoding, list):205+ accept_encoding = ','.join(accept_encoding)206+ else:207+ accept_encoding = 'gzip,deflate'208+ headers['accept-encoding'] = accept_encoding209+210+ if user_agent:211+ headers['user-agent'] = user_agent212+213+ if keep_alive:214+ headers['connection'] = 'keep-alive'215+216+ if basic_auth:217+ headers['authorization'] = 'Basic ' + \218+ b64encode(six.b(basic_auth)).decode('utf-8')219+220+ return headers221+222+223 def is_connection_dropped(conn):224 """225 Returns True if the connection is dropped and should be closed.226 227 :param conn:161- ``HTTPConnection`` object.228+ :class:`httplib.HTTPConnection` object.229 230 Note: For platforms like AppEngine, this will always return ``False`` to231 let the platform handle connection recycling transparently for us.232 """4 unmodified lines237 if not poll: # Platform-specific238 if not select: # Platform-specific: AppEngine239 return False240 241+ try:174- return select([sock], [], [], 0.0)[0]242+ return select([sock], [], [], 0.0)[0]243+ except SocketError:244+ return True245 246 # This version is better on platforms that support it.247 p = poll()248 p.register(sock, POLLIN)4 unmodified linesmodified:HISTORY.rst+8 added
1 unmodified line2 3 History4 -------5 6+0.13.4 (2012-xx-xx)7++++++++++++++++++++8+9+- Fix leaking connections (from urllib3 update)10+- OAuthlib path hack fi11+- App Engine 2.7 Fixes!12+13+14 0.13.3 (2012-07-12)15 +++++++++++++++++++16 17 - Use simplejson if available.493 unmodified lines