如何合并 Flask 网站的两个 HTML 按钮?



我正在用python构建一个网站,我希望能够通过一个按钮启动和停止"motiondetect.py"。(合并两个按钮( 现在我有两个单独的"开始运动检测"和">停止运动检测"按钮。我希望合并的*按钮在您第一次单击时启动运动检测,第二次单击应该停止它。

以下是我的代码片段:

Python Start:

@app.route("/start", methods=["GET", "POST"])
def start_motion():
global proc
#global FNULL
#global APP_ROOT
print(" > Start")
proc = subprocess.Popen(["python", "motiondetect.py"])#, stdout=FNULL, 
stderr=subprocess.STDOUT)
print(" > Process id {}".format(proc.pid))
return "Start Detection"

网页开始:

$(document).ready(function(){
$("#start_button").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/start",
data: {},
success:function(result){
$("#start_button").html(result);
}});
});
});

蟒蛇停止:

@app.route("/stop", methods=["GET", "POST"])
def stop_motion():
global proc
print(" > Stop")
proc.kill()
#os.system("echo > close")
#print(" > Process killed")
#time.sleep(2)
#os.system("rm close")
return "Stop Detection"

目录停止:

$(document).ready(function(){
$("#stop_button").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/stop",
data: {},
success:function(result){
$("#stop_button").html(result);
}});
});

感谢您的时间和对我的无知的痛苦。

好的,为了您的方便,我制作了一个示例来向您简要介绍这些想法。因此,这是您可以在烧瓶部分执行的操作。

from Flask import request
@app.route("/start", methods=["GET", "POST"])
def start_motion(request):
global proc
#global FNULL
#global APP_ROOT
data = json.loads(request.data.decode("utf-8"))
#data here is {'exam': 'a text'} a dict in this case
state = data["state"]
if (state and state=="start"):
print(" > Start")
proc = subprocess.Popen(["python", "motiondetect.py"])#, stdout=FNULL, 
stderr=subprocess.STDOUT
print(" > Process id {}".format(proc.pid))
return "Start Detection"
else:
print("the state is blank or is not requesting to start")
@app.route("/stop", methods=["GET", "POST"])
def stop_motion(request):
global proc
print(" > Stop")
data = json.loads(request.data.decode("utf-8"))
#data here is {'exam': 'a text'} a dict in this case
state = data["state"]
if (state and state=="start"):
proc.kill()
#os.system("echo > close")
#print(" > Process killed")
#time.sleep(2)
#os.system("rm close")
else:
print("state is either blank or not stop")
return "Stop Detection"

我只是添加了代码以接收来自 Ajax 调用的state数据,并在后端继续。

来到你的 HTML 和 Javascript 方面,这是你可以做的:

$(document).ready(function(){
$("#motion_button").click(function(e){
e.preventDefault();
state = $(this).attr('value'); 
if(state=="start")
{
$("#motion_button").attr("value")= "stop";
$("#motion_button").text("Stop")
callurl="/start"
}
elseif(state=="stop")
{
$("#motion_button").attr("value")= "start";
$("#motion_button").text("Start")
callurl="/stop"
}

$.ajax({type: "POST",
url: "/start",
data: {"state":state},
success:function(result){
$("#start_button").html(result);
}});
});
});

由于使用POST方法发送数据,因此可能还必须考虑发送csrf令牌。我希望您了解前端代码,因为它们非常简单。另供参考,请查看我的答案 无法从包含完整示例的 JS AJAX 将数据发送回 Django。

最新更新