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

时间:2019-04-08 08:08:52

标签: javascript python jquery ajax flask

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

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

began

那是我的index.html

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)

如果我运行flask网站并单击按钮,我想执行保存在项目文件夹或其他位置的test.py。我不知道这种方法是否可行,或者是否有更好的解决方案。现在,我仍在尝试使用flask,但是无法运行test.py。 当我按下按钮时,它只会显示[object Object]

的警报

基本上,我要构建的是一个带有按钮的网站,例如一项在后台运行我的脚本的服务,有时可能需要更多时间才能完成。 我不确定在这种情况下是否误解了ajax的使用。 任何帮助都很好。

2 个答案:

答案 0 :(得分:1)

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

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>

答案 1 :(得分:0)

一些使用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>

相关问题