为了账号安全,请及时绑定邮箱和手机立即绑定

使用我的网站上的按钮运行python脚本

使用我的网站上的按钮运行python脚本

繁华开满天机 2021-04-06 20:19:44
我目前正在尝试使用Flask创建一个仅包含一个按钮的网站(目前)。如果我按下该按钮,我想从特定路径或仅在项目文件夹中运行python脚本。我已经看到了一些关于同一主题的帖子,但是它们都无法真正帮助我。我已经有一些代码了。这是我的Flask app.pyfrom flask import Flask, render_template, jsonifyimport testapp = Flask(__name__)@app.route('/')def index():    return render_template('index.html')if __name__ == '__main__':app.run(debug=True)那就是我的index.html<!DOCTYPE html><html> <head> </head> <body>   <input type="button" id='script' name="scriptbutton" value=" Run Script " onclick="goPython()">   <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>   <script>       function goPython(){           $.ajax({             type: 'POST',             url: "/test.py",             //or some other path like /scripts/test.py             dataType: "text",             success: function (data) {               alert(data)             },             error: function (data) {               alert(data)             }           });       }   </script> </body></html>如果我运行烧瓶网站,然后单击按钮,我要执行保存在项目文件夹或其他位置的test.py。我不知道这种方法是否可行,或者是否有更好的解决方案。现在,我仍在尝试使用flask,但是无法运行test.py。当我按下按钮时,它只向我显示[object Object]的警报基本上,我要建立的网站是带有按钮的网站,例如一项在后台运行我的脚本的服务,有时可能需要更多时间才能完成。我不确定在这种情况下是否误解了ajax的使用。你能帮忙的话,我会很高兴。
查看完整描述

2 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

下面是在按钮按下时运行代码的简单解决方案。如果要在后台运行任务,请查看芹菜或烧瓶中的线程。


from flask import Flask, render_template, jsonify

import test


app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])

def index():

    if request.method == "POST":

        <insert python script here>


    return render_template('index.html')

将您的模板更改为此:


<!DOCTYPE html>

<html>

  <head>

  </head>

  <body>

    <form  method = "post">

     <input type="button" id='script' name="submit" value="Run Script">

    </form>

  </body>

</html>


查看完整回答
反对 回复 2021-04-22
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

一些使用Flask函数,Jquery和Bootstrap的示例(不是必需的,仅用于按钮格式设置)。希望这可以对您有所帮助。Python(在应用脚本中):


    @app.route('/do_something')

    def do_something():

        """

        Do something on button press.

        """

        # your code

        return res

Javascript:



    var btnName = function(){

        $.get('/do_something',

             function(x){

                         $("#resBtnHere").html(x);

                         }

             )

    }

    btnName()


html中的按钮: <button type="button" class="btn btn-primary" onclick="btnName()">Click here</button>


在html中,按功能的结果(如果需要): <p id="resBtnHere"></p>


查看完整回答
反对 回复 2021-04-22
  • 2 回答
  • 0 关注
  • 248 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信