Flask Web 应用程序:使用 AJAX 控制进程
<!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><button id='start'>开始</button>
<button id='stop'>停止</button>
<div id='output'></div>
<script>
$(document).ready(function() {
$("#start").click(function() {
$.ajax({
url: "/execute",
type: "POST",
data: {
action: "start"
},
success: function(response) {
$("#output").html(response.output);
}
});
});
$("#stop").click(function() {
$.ajax({
url: "/execute",
type: "POST",
data: {
action: "stop"
},
success: function(response) {
$("#output").html(response.output);
}
});
});
});
</script>
</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>
原文地址: https://www.cveoy.top/t/topic/qys1 著作权归作者所有。请勿转载和采集!