You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Mongoose HTTP服务器接口耗时2秒,求原因排查

Python请求Mongoose HTTP Server耗时2秒的原因及解决方法

你的Python请求耗时远高于Java/NodeJS,大概率是下面几个原因导致的,对应解决方案可以逐一排查:

1. localhost解析延迟(最常见)

Python的urllib在解析localhost时,可能会优先尝试IPv6地址,如果你的Mongoose服务器只监听IPv4,就会出现IPv6连接超时(通常约2秒)后才 fallback到IPv4的情况,刚好匹配你遇到的耗时。

解决方法:

  • 直接把请求URL里的localhost换成127.0.0.1,跳过DNS解析步骤:
    url = "http://127.0.0.1:8080/api"
    
  • 检查系统hosts文件,确保localhost只映射到127.0.0.1,或者注释掉IPv6的映射条目(比如::1 localhost)。

2. 未启用TCP_NODELAY导致Nagle算法延迟

Nagle算法会合并小数据包再发送,对于你的pingSession这类小请求,可能会等待约2秒才发送,而Java和NodeJS默认会启用TCP_NODELAY禁用这个算法。

解决方法:
自定义HTTPHandler来设置TCP_NODELAY选项,修改代码如下:

import json
import socket
from urllib import request
from datetime import datetime

class NoDelayHTTPHandler(request.HTTPHandler):
    def http_open(self, req):
        return self.do_open(self.create_connection, req)
    
    def create_connection(self, host, port=None, timeout=None):
        sock = socket.create_connection((host, port), timeout)
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
        return sock

# 安装带TCP_NODELAY的opener
opener = request.build_opener(NoDelayHTTPHandler)
request.install_opener(opener)

url = "http://localhost:8080/api"

myData = {
            "schema": "jsonCommand.org/v1",
            "requestId": 1,
            "api": "admin",
            "apiVersion": "1.0",
            "action": "pingSession"
        }

data = json.dumps(myData).encode()

for i in range(0, 10):
    now = datetime.now()
    print('Current DateTime:', now)
    # 循环内创建新的请求对象
    req = request.Request(url, method="POST")
    req.add_header('Content-Type', 'application/json')
    req.add_header("Connection", "Close")
    with request.urlopen(req, data=data) as response:
        body = response.read()
        print(body)

3. 请求对象复用的状态问题

你原本在循环外创建Request对象,虽然设置了Connection: Close,但urllib的请求对象可能保留了一些异常状态,导致每次请求的初始化流程变慢。

解决方法:
把Request对象的创建移到循环内部,确保每次请求都是全新的对象(如上面代码所示)。

内容的提问来源于stack exchange,提问作者Ray Hulha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:41:43