Skip to main content
 首页 » 编程设计

python之为什么我从 urllib2 发出的请求被 Apache2 延迟了

2025年05月04日19sky-heaven

我正在处理两台内部 Web 服务器,一台在 Ubuntu Server 10.04 上运行 Apache2,另一台在 Windows Server 2008 上运行 IIS。当我从缓存已清除的 Web 浏览器访问任一根 URL 时,调用服务器通过 IP 地址,两者都会立即弹出。我也没有看到任何服务器上浏览网站的延迟。但是,当我在 Python 中使用 urllib2 调用相同的地址时,对 Apache2 服务器的每个请求都会延迟 4.5 到 5 秒。 IIS 服务器响应时间小于 0.02。

这是我运行的脚本来验证问题。我设置了 User-Agent 以防它有所作为,但它似乎没有:

import urllib2 
from time import time 
 
apache_server = 'http://192.168.1.101/' 
iis_server = 'http://192.168.1.102/' 
 
headers = {'User-Agent' : "Mozilla/5.0 (X11; U; Linux i586; de; rv:5.0) Gecko/20100101 Firefox/5.0",} 
 
print('Contacting Apache2 server...') 
request = urllib2.Request(url=apache_server, headers=headers) 
start = time() 
response = urllib2.urlopen(request).read() 
elapsed = time() - start 
print('Elapsed time: {0}'.format(elapsed)) 
 
print('Contacting IIS server...') 
request = urllib2.Request(url=iis_server, headers=headers) 
start = time() 
response = urllib2.urlopen(request).read() 
elapsed = time() - start 
print('Elapsed time: {0}'.format(elapsed)) 

结果:

>python urltest.py 
Contacting Apache2 server... 
Elapsed time: 4.55500006676 
 
Contacting IIS server... 
Elapsed time: 0.0159997940063 

浏览器请求和我的 urllib2 请求之间有什么区别可以解释这种延迟?

我已经看到由反向 DNS 查找引起的 SSH 的类似问题,但我的 Apache2 配置中有 HostnameLookups Off。我不知道是否还有其他事情可以触发查找。


更新:我跟踪了与 Wireshark 的交流,发现三个失败的 NBNS 查询从我的机器到 Apache2 服务器,然后才开始交谈。这占了损失的时间。我尝试在 hosts 中为 Web 服务器添加一个条目,这消除了延迟。

我没有将此添加为答案,因为我仍然不知道为什么会进行查找尝试,或者为什么我在 Web 浏览器中看不到相同的行为。无论我犯了什么错误,我都有一个解决方法。

请您参考如下方法:

进行查找是因为 Windows 就是这样做的。它总是先检查 NetBIOS。

进一步阅读: