1 from __future__ import absolute_import
4 from select import poll, POLLIN
5 except ImportError: # `poll` doesn't exist on OSX and other platforms
8 from select import select
9 except ImportError: # `select` doesn't exist on AppEngine.
13 def is_connection_dropped(conn): # Platform-specific
15 Returns True if the connection is dropped and should be closed.
18 :class:`httplib.HTTPConnection` object.
20 Note: For platforms like AppEngine, this will always return ``False`` to
21 let the platform handle connection recycling transparently for us.
23 sock = getattr(conn, 'sock', False)
24 if sock is False: # Platform-specific: AppEngine
26 if sock is None: # Connection already closed (such as by httplib).
30 if not select: # Platform-specific: AppEngine
34 return select([sock], [], [], 0.0)[0]
38 # This version is better on platforms that support it.
40 p.register(sock, POLLIN)
41 for (fno, ev) in p.poll(0.0):
42 if fno == sock.fileno():
43 # Either data is buffered (bad), or the connection is dropped.
47 # This function is copied from socket.py in the Python 2.7 standard
48 # library test suite. Added to its signature is only `socket_options`.
49 def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
50 source_address=None, socket_options=None):
51 """Connect to *address* and return the socket object.
53 Convenience function. Connect to *address* (a 2-tuple ``(host,
54 port)``) and return the socket object. Passing the optional
55 *timeout* parameter will set the timeout on the socket instance
56 before attempting to connect. If no *timeout* is supplied, the
57 global default timeout setting returned by :func:`getdefaulttimeout`
58 is used. If *source_address* is set it must be a tuple of (host, port)
59 for the socket to bind as a source address before making the connection.
60 An host of '' or port 0 tells the OS to use the default.
64 if host.startswith('['):
65 host = host.strip('[]')
67 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
68 af, socktype, proto, canonname, sa = res
71 sock = socket.socket(af, socktype, proto)
73 # If provided, set socket level options before connecting.
74 # This is the only addition urllib3 makes to this function.
75 _set_socket_options(sock, socket_options)
77 if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
78 sock.settimeout(timeout)
80 sock.bind(source_address)
84 except socket.error as e:
93 raise socket.error("getaddrinfo returns an empty list")
96 def _set_socket_options(sock, options):
101 sock.setsockopt(*opt)