T.Coutlakis
T.Coutlakis

Reputation: 2771

Python requests not closing TCP connection after timeout

I am using Python3.2 that ships with Debian on the latest Raspberry Pi:

try:
   headers = {
      'Content-Type': 'application/json',
      'Connection': 'close',
   }
   s = requests.session()
   s.keep_alive = False

   response = s.get('http://example.com/', headers=headers, timeout=1)
except Exception as e:
   s.close()
   print(repr(e))

The server doesn't reply in time, so the script times out, and raises the Exception. However the client then leaves the connection lingering open.

I would like the connection to close after a timeout occurs?

I understand the concept at the TCP protocol level, however I don't see any documentation online for how to do something as simple as this in python-requests.

Upvotes: 3

Views: 4069

Answers (2)

Sina Khelil
Sina Khelil

Reputation: 1991

Wrap it in a with statement, then move the s.close() to a finally: after the except:

with requests.session() as s:
    s.keep_alive = False
    try:
       headers = {
          'Content-Type': 'application/json',
          'Connection': 'close',
       }

       response = s.get('http://example.com/', headers=headers, timeout=1)
    except Exception as e:
       print(repr(e))
    finally:
       s.close()

The s.close() will run every time, whether it succeeds or fails. the with statement should provide the extra insurance since the whole thing will run in that context

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137547

I'm assuming you're seeing these connections in something like tcpdump.

TCP connections linger (in the kernel) by design, for a period of time. There's really nothing you can do about it.

Upvotes: 1

Related Questions