我在最新的Raspberry Pi上使用Debian附带的Python3.2:
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))
服务器没有及时回复,因此脚本超时,并引发异常。但是,客户端会使连接保持打开状态。
我想在超时发生后关闭连接?
我理解TCP协议级别的概念,但我没有在网上看到任何关于如何在python请求中执行简单操作的文档。
答案 0 :(得分:1)
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
答案 1 :(得分:1)
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.