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

如何基于Python/Flask实现无刷新页面动态展示HTTP请求数据

Flask 实现无刷新实时展示HTTP请求并返回Payload

核心需求

搭建Flask页面完成两个核心功能:

  1. 无需手动刷新页面,自动实时展示所有收到的HTTP请求内容
  2. 收到请求后,将请求的payload原样返回给调用服务

现有方案问题分析

你尝试的几种方案均无法实现实时自动更新,问题点如下:

  • iframe流方案:混淆了请求处理接口和页面展示逻辑,/request是处理POST请求的接口,iframe发起的GET请求无法触发新请求推送,且每次请求都是独立连接,无法持续更新页面
  • after_request装饰器:仅在响应单个请求后执行渲染操作,无法主动向已打开的页面推送更新,页面不会自动刷新
  • AJAX按钮触发:需要手动操作才能更新,不符合"实时自动更新"的需求

可行解决方案:Server-Sent Events(SSE)

SSE是一种服务器单向推送数据到客户端的技术,适合这种仅需服务器主动推送更新的场景,实现简单且无需额外依赖。

改进后的完整代码

app.py

from flask import Flask, request, render_template, Response, jsonify
import time

app = Flask(__name__, template_folder='')
responses = []

# 主页路由,返回带初始请求列表的页面
@app.route('/')
def index():
    return render_template('index.html', initial_responses=responses)

# 处理请求接口:存储请求并返回payload给调用方
@app.route('/request', methods=['GET', 'POST'])
def handle_request():
    req_payload = request.json
    if req_payload:
        responses.append(req_payload)
        print(f"收到请求: {req_payload}")
    # 将收到的payload原样返回
    return jsonify(req_payload) if req_payload else jsonify({})

# SSE流路由:持续向客户端推送新请求
@app.route('/stream')
def stream():
    def event_stream():
        last_count = len(responses)
        while True:
            # 检查是否有新请求产生
            if len(responses) > last_count:
                new_resp = responses[-1]
                # 按SSE格式返回数据
                yield f'data: {new_resp}

'
                last_count = len(responses)
            time.sleep(1)  # 每秒检查一次,避免资源占用过高
    return Response(event_stream(), mimetype='text/event-stream')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=81, debug=True)

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Flask 请求实时展示页面</title>
    <style>
        #request-list {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            min-height: 200px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <h3>Flask 请求实时展示</h3>
    <div id="request-list">
        <!-- 渲染初始请求列表 -->
        {% for resp in initial_responses %}
            <div>{{ resp }}</div>
        {% endfor %}
    </div>

    <script>
        // 建立SSE连接
        const eventSource = new EventSource('/stream');
        
        // 监听服务器推送的新请求
        eventSource.onmessage = function(event) {
            const requestList = document.getElementById('request-list');
            const newItem = document.createElement('div');
            newItem.textContent = event.data;
            requestList.appendChild(newItem);
        };

        // 处理连接异常
        eventSource.onerror = function(error) {
            console.error('SSE连接异常:', error);
            eventSource.close();
        };
    </script>
</body>
</html>

使用说明

  1. 启动Flask服务
  2. 通过你的JSONGETRequest类或Postman等工具调用/request接口发送请求
  3. 打开主页http://localhost:81,新请求会自动实时展示在页面上,无需刷新
  4. 调用服务会收到发送的payload作为响应

额外注意事项

  • 测试环境下全局列表responses可以正常使用,生产环境需添加threading.Lock()保证线程安全
  • SSE默认支持连接断开后自动重连,适合长时间保持页面在线的场景
  • 如果需要双向通信,可替换为WebSocket,但SSE对单向推送场景更轻量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:05:30