Skip to main content
 首页 » 编程设计

python之为什么一些相同的 POST 请求花费的时间比其他请求长两到三倍

2024年12月31日7bonelee

我想发送几十个 POST 请求,每个请求间隔 50 毫秒。所有请求都是相同的。它们大约需要 315 毫秒(发送时间 + 延迟),但出于一个原因我忽略了四分之一的请求(平均而言)需要两到三倍的时间(请参见下面的 Charles Proxy 时间线图表)。

谁能告诉我为什么?是不是因为多线程的实现不好(见下面的代码)?

import thread 
import time 
import requests 
from requests.packages.urllib3.exceptions import InsecureRequestWarning 
 
url = XXX 
req_data = XXX 
 
session = requests.Session() 
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 
session.cookies.clear() 
 
def send_request(url, data): 
    r = session.post(url, verify=False, data=data) 
 
for i in range(20): 
    time.sleep(0.050) 
    thread.start_new_thread( send_request, (url, req_data,) ) 

Charles 文档中的图例:

Each bar on the chart is divided into three segments:

  • Request - the time spent sending (uploading) the request (dark blue)
  • Latency - the time spent waiting for network latency or processing time on the server (mid blue)
  • Response - the time spent receiving (downloading) the response (light blue)

编辑:

我通过 Wireshark 分析了连接,下面是一个 ~300 毫秒请求和一个 ~800 毫秒请求的示例。

800ms好像比300ms多了两个ACK包。任何人都知道发生了什么以及这两个请求之间有什么不同?

300 毫秒请求

800 毫秒请求

请您参考如下方法:

使用 Wireshark 进行的数据包分析(参见主帖中的编辑)表明,两个查询(一个短查询和一个长查询)之间的 500 毫秒间隔来自 SSL key 交换时的 ACK 数据包。

提醒一下,我的所有请求都通过代理 Charles Web Proxy。

经过一些测试,问题似乎出在使用 Charles 进行 SSL 验证(有时会增加 500ms 的请求上传时间)。

在以下情况下,查询具有等效且规则的发送时间:

  • 当我不使用 Charles 代理时
  • 当我使用代理 Charles 但我通过“http”而不是 “https”(无 SSL)(这是我在这里保留的解决方案,因为没有敏感 数据)。

谢谢你们的帮助:)

这个答案显示了 Charles Web Proxy 的 SSL 认证与问题之间的联系,但没有充分解释