本教程演示如何使用 Flask 和 SocketIO 创建一个 Web Ping 应用,将 ping 命令的输出实时显示在网页上。

首先,需要安装 flask-socketio 库:

pip install flask-socketio

然后,修改代码如下:

import subprocess
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO

app = Flask(__name__, template_folder='D:\python\webping')
app.config['SECRET_KEY'] = 'secret_key'
socketio = SocketIO(app)

process = None

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start', methods=['POST'])
def start():
    global process
    if process:
        return jsonify({'message': 'Command already running.'})

    process = subprocess.Popen(['ping', '-t', '114.114.114.114'], stdout=subprocess.PIPE, universal_newlines=True)

    def stream():
        i = 0
        while process and process.poll() is None:
            output = process.stdout.readline().strip()

            i+=1
            print(i,output)
            socketio.emit('stream_output', output)
        
    socketio.start_background_task(stream)
    return jsonify({'message': 'Command started.'})

@app.route('/stop', methods=['POST'])
def stop():
    global process
    if process:
        process.terminate()
        process = None
        return jsonify({'message': 'Command stopped.'})
    else:
        return jsonify({'message': 'No command running.'})

if __name__ == '__main__':
    socketio.run(app)

然后,在 index.html 文件中添加以下代码:

<!DOCTYPE html>
<html>
<head>
    <title>Web Ping</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.1/socket.io.js'></script>
</head>
<body>
    <h1>Web Ping</h1>
    <button id='start-button'>Start</button>
    <button id='stop-button'>Stop</button>
    <div id='output'></div>

    <script>
        var socket = io();

        socket.on('stream_output', function(output) {
            var outputDiv = document.getElementById('output');
            outputDiv.innerHTML += output + '<br>';
        });

        document.getElementById('start-button').addEventListener('click', function() {
            fetch('/start', {method: 'POST'})
                .then(response => response.json())
                .then(data => console.log(data));
        });

        document.getElementById('stop-button').addEventListener('click', function() {
            fetch('/stop', {method: 'POST'})
                .then(response => response.json())
                .then(data => console.log(data));
        });
    </script>
</body>
</html>

这样,当点击“Start”按钮时,会启动 ping 命令并将输出实时显示在网页上;点击“Stop”按钮时,会停止 ping 命令。

Flask Web Ping 实时输出:使用 SocketIO 实现

原文地址: https://www.cveoy.top/t/topic/qyCV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录