Python请求关闭连接



我有一个python请求来捕获令牌号,之后我使用这个令牌来运行另一个API url,之后我想关闭当前会话,但我不能,像这样:

url = 'https://10.10.20.21/tron/api/v1/tokens'
payload = {'grant_type': 'password', 'username': 'login', 'password': 'test@2021'}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url, headers=headers, data=payload, verify=False)

如果我打印文本和标题,可以看到:

print(f'text: {response.text}')
print(f'request.headers: {response.request.headers}')
text: "Maximum number of active sessions reached"
request.headers: {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '57', 'Content-Type': 'application/x-www-form-urlencoded'}

所以,我想关闭当前会话/连接,但即使当我运行response.close()连接仍然存在:

response.close()

我的愿望是关闭这个会话,以便运行另一个会话。

我发现自己在与华硕Aura Rest API相同的情况下,在我不知道缺乏端口号之后?Rest API服务器崩溃。似乎,尽管request.Session的实现,我还必须添加标题:{'Connection':'close'}到会话所以现在只有挂起的连接可见netstat -aon | findstr 27339目前,它修复了这个问题,代码看起来像这样:

def aura_command(self, command):
aura_session = requests.Session()
try:
aura_session.verify = False
aura_session.headers.update({'Connection':'close'})
self.aura_connection(command, aura_session)
except requests.exceptions.ConnectionError:
print('init_aura error')
finally:
print('closing session')
aura_session.close()
def aura_connection(self, command, aura_session):
if command == 'init':
aura_session.post(self.aura_sdk_url, json=self.aura_init)
elif command == 'stealth':
aura_session.put(self.aura_sdk_url + '/AuraDevice', json=self.aura_stealth)
elif command == 'intruder':
aura_session.put(self.aura_sdk_url + '/AuraDevice', json=self.aura_intruder)
elif command == 'windows':
aura_session.put(self.aura_sdk_url + '/AuraDevice', json=self.aura_windows)
elif command == 'deinit':
aura_session.delete(self.aura_sdk_url, json=self.aura_init)```

我建议查看requests.Session对象。他们可能会给你你正在寻找的功能。

from requests import Session
url = 'https://10.10.20.21/tron/api/v1/tokens'
payload = {'grant_type': 'password', 'username': 'login', 'password': 'test@2021'}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
sess = Session()
sess.verify = False
sess.headers.update(headers)
response = sess.post(url, data=payload)
sess.close()

最新更新