我在最新的 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 协议(protocol)级别的概念,但是我没有在网上看到任何关于如何在 python 请求中执行如此简单的操作的文档。
请您参考如下方法:
将其包装在with 语句中,然后将s.close() 移动到finally: 之后的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()
s.close() 每次都会运行,无论是成功还是失败。 with 语句应该提供额外的保险,因为整个事情将在该上下文中运行
