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

Python Quart中混用HTTP与WebSocket出现握手错误的问题排查

问题排查与解决思路

核心原因:路由路径冲突

Quart中如果同一个路径(比如/gen-image)同时注册了HTTP路由(@app.route)和WebSocket路由(@app.websocket),会直接导致请求处理逻辑冲突。当WebSocket客户端发起握手请求时,HTTP路由会优先拦截请求并返回HTTP响应,而非完成WebSocket握手流程,最终触发"websocket: bad handshake"错误。

具体解决方法

1. 给WebSocket路由配置独立路径(推荐)

最简单可靠的方式是让WebSocket和HTTP路由使用不同路径,避免冲突:

# HTTP请求路由
@app.route('/gen-image', methods=['POST'])
async def gen_image_http():
    # 处理普通HTTP请求逻辑
    return jsonify({"status": "processing"})

# WebSocket通信路由
@app.websocket('/gen-image/ws')
async def gen_image_ws():
    # 处理WebSocket消息交互逻辑
    while True:
        task_data = await websocket.receive_json()
        # 执行生成图片的任务并推送进度
        await websocket.send_json({"progress": 50})

客户端只需连接ws://your-domain/gen-image/ws即可正常完成握手。

2. 检查Quart启动方式与版本

确保使用ASGI兼容的方式启动Quart,不要沿用Flask的启动逻辑:

# 用hypercorn启动(Quart官方推荐的ASGI服务器)
hypercorn your_app_module:app

同时确认使用最新版Quart,旧版本可能存在路由优先级的bug:

pip install --upgrade quart

3. 排查客户端与代理配置

  • 客户端必须使用ws://(或wss://)协议发起连接,不能用http://
  • 如果有反向代理(如Nginx),需确保配置正确转发WebSocket握手头:
location /gen-image/ws {
    proxy_pass http://127.0.0.1:5000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 06:04:53