Flask Web 应用:使用 iperf3 命令进行网络性能测试
这个程序是一个基于 Flask 的 Web 应用程序,可以通过发送 HTTP 请求来启动、停止和获取命令的输出。但是,这个程序的 stream 函数无法正确地将命令的输出返回给客户端。
要解决这个问题,可以按照以下步骤进行修改:
- 定义一个新的列表 'stream_list' 用于存储命令的输出。
- 将 'output_list' 和 'stream_list' 都定义为全局变量。
- 在 'start' 函数中,将命令的输出写入 'stream_list'。
- 在 'stream' 函数中,将 'stream_list' 的内容返回给客户端,并清空 'stream_list'。
- 在 'stop' 函数中,停止命令的执行,并清空 'stream_list'。
修改后的代码如下所示:
# app.py
import subprocess
from flask import Flask, render_template, request, jsonify, Response
app = Flask(__name__)
process = None
output_list = []
stream_list = []
@app.route('/')
def index():
return render_template('index.html')
@app.route('/start', methods=['POST'])
def start():
global process, output_list, stream_list
if process:
return jsonify({'message': 'Command already running.'})
process = subprocess.Popen(['iperf3', '-s', '-p', '1111'], stdout=subprocess.PIPE, universal_newlines=True)
def stream():
while process and process.poll() is None:
output = process.stdout.readline().strip()
stream_list.append(output)
return Response(stream(), mimetype='text/plain')
@app.route('/stream')
def stream():
global stream_list
if stream_list:
def generate():
while stream_list:
output = stream_list.pop(0)
yield output + '
'
return Response(generate(), mimetype='text/event-stream')
else:
return jsonify({'message': 'No command running.'})
@app.route('/stop', methods=['POST'])
def stop():
global process, output_list, stream_list
if process:
process.terminate()
process = None
output_list = []
stream_list = []
return jsonify({'message': 'Command stopped.'})
else:
return jsonify({'message': 'No command running.'})
if __name__ == '__main__':
app.run()
这样修改后,应用程序将能够正确地将命令的输出返回给客户端。
原文地址: https://www.cveoy.top/t/topic/qx7M 著作权归作者所有。请勿转载和采集!