<!DOCTYPE html>
<html>
<head>
    <title>Flask Web Application</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
</head>
<body>
    <h1>Flask Web Application</h1>
<pre><code>&lt;button id='start'&gt;开始&lt;/button&gt;
&lt;button id='stop'&gt;停止&lt;/button&gt;

&lt;div id='output'&gt;&lt;/div&gt;

&lt;script&gt;
    $(document).ready(function() {
        $(&quot;#start&quot;).click(function() {
            $.ajax({
                url: &quot;/execute&quot;,
                type: &quot;POST&quot;,
                data: {
                    action: &quot;start&quot;
                },
                success: function(response) {
                    $(&quot;#output&quot;).html(response.output);
                }
            });
        });
        
        $(&quot;#stop&quot;).click(function() {
            $.ajax({
                url: &quot;/execute&quot;,
                type: &quot;POST&quot;,
                data: {
                    action: &quot;stop&quot;
                },
                success: function(response) {
                    $(&quot;#output&quot;).html(response.output);
                }
            });
        });
    });
&lt;/script&gt;
</code></pre>
</body>
</html>
<pre><code class="language-python">import subprocess
from flask import Flask, render_template, request, jsonify, make_response, redirect

app = Flask(__name__)
process = None

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

@app.route('/execute', methods=['POST'])
def execute():
    global process
    if request.form['action'] == 'start':
        if process is not None and process.poll() is None:
            # 如果进程正在运行,则不执行新的命令
            return jsonify({'output': '进程正在运行,请先停止'})
        process = subprocess.Popen(['ping', '1.1.1.1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        output, error = process.communicate()
        return jsonify({'output': output.decode('utf-8')})
    elif request.form['action'] == 'stop':
        if process is not None and process.poll() is None:
            # 如果进程正在运行,则停止进程
            process.terminate()
            process.wait()
            process = None
        return jsonify({'output': '进程已停止'})
    else:
        return make_response(jsonify({'error': '无效的动作'}), 400)

if __name__ == '__main__':
    app.run(debug=True)
</code></pre>
Flask Web 应用程序:使用 AJAX 控制进程

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

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