猿问

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

我目前正在尝试使用Flask创建一个仅包含一个按钮的网站(目前)。如果我按下该按钮,我想从特定路径或仅在项目文件夹中运行python脚本。我已经看到了一些关于同一主题的帖子,但是它们都无法真正帮助我。


我已经有一些代码了。这是我的Flask app.py


from flask import Flask, render_template, jsonify

import test


app = 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的使用。你能帮忙的话,我会很高兴。


繁华开满天机
浏览 249回答 2
2回答

拉莫斯之舞

下面是在按钮按下时运行代码的简单解决方案。如果要在后台运行任务,请查看芹菜或烧瓶中的线程。from flask import Flask, render_template, jsonifyimport testapp = Flask(__name__)@app.route('/', methods=['POST', 'GET'])def index():&nbsp; &nbsp; if request.method == "POST":&nbsp; &nbsp; &nbsp; &nbsp; <insert python script here>&nbsp; &nbsp; return render_template('index.html')将您的模板更改为此:<!DOCTYPE html><html>&nbsp; <head>&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <form&nbsp; method = "post">&nbsp; &nbsp; &nbsp;<input type="button" id='script' name="submit" value="Run Script">&nbsp; &nbsp; </form>&nbsp; </body></html>

慕妹3146593

一些使用Flask函数,Jquery和Bootstrap的示例(不是必需的,仅用于按钮格式设置)。希望这可以对您有所帮助。Python(在应用脚本中):&nbsp; &nbsp; @app.route('/do_something')&nbsp; &nbsp; def do_something():&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; Do something on button press.&nbsp; &nbsp; &nbsp; &nbsp; """&nbsp; &nbsp; &nbsp; &nbsp; # your code&nbsp; &nbsp; &nbsp; &nbsp; return resJavascript:&nbsp; &nbsp; var btnName = function(){&nbsp; &nbsp; &nbsp; &nbsp; $.get('/do_something',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;function(x){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$("#resBtnHere").html(x);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;)&nbsp; &nbsp; }&nbsp; &nbsp; btnName()html中的按钮: <button type="button" class="btn btn-primary" onclick="btnName()">Click here</button>在html中,按功能的结果(如果需要): <p id="resBtnHere"></p>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答