【问题标题】:How to merge two HTML buttons for a Flask website?如何合并 Flask 网站的两个 HTML 按钮?
【发布时间】:2019-01-19 09:42:46
【问题描述】:

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

这是我的代码 sn-ps:

Python 开始:

@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"

Html 开始:

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

    });

Python 停止:

@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"

HTML 停止:

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

感谢您的宝贵时间,并为我的无知感到抱歉。

【问题讨论】:

  • 您可能需要将按钮单击的状态存储在某处,可能在前端,例如当用户第一次单击按钮时,您应该保存一个状态first,当用户单击时再次,然后您将拥有一个状态second,以便您可以随后终止该进程,该用户已第二次单击该按钮。您也可以更改按钮中的文本,最初可能是start,一旦用户点击start,文本可以动态更改为stop
  • @user2906838 我猜你是对的。我对网络开发真的很陌生,所以请原谅我,但我将如何将它存储在前端。作为python中的变量?如果不是要求太多,你能给我一个例子吗?无论如何谢谢!
  • 好的,那我给你准备一个解决方案。
  • 我给你写了一个例子,请查收。

标签: python html button flask


【解决方案1】:

好的,为了您的方便,我制作了一个示例来向您简要介绍这些想法。所以这就是你可以在你的 Flask 部分做的事情。

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 令牌。我希望你理解前端代码,因为它们非常简单。另外作为参考,请查看我的答案Can't send data back to Django from JS AJAX,其中包含一个完整的示例。

【讨论】:

  • 谢谢你们的回答,你们太棒了!仍然没有工作,但你让我走上了正确的道路。让我做更多的研究,我会回复你!!!
  • 好吧,这就是主意。您还可以进一步说明究竟是什么不起作用。上面的代码是为了举例。
猜你喜欢
  • 2021-09-28
  • 2017-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 2016-03-30
相关资源
最近更新 更多