使用 Flask 将 JavaScript 连接到 Python 脚本

Leo*_*oFr 4 javascript python web-frameworks flask

我完全自己用 HTML/CSS 创建了一个网站。还可以将 Javascript 用于事件(单击按钮,...)。

现在我想用它连接一个 python 脚本,更重要的是,将结果从 python 返回到我的网站并在那里显示(使用)它们。考虑这样的事情:

带有输入和按钮的网站。如果您单击按钮,则应运行 python 脚本,如果输入是奇数或偶数,则返回该脚本(当然,对于这种特定情况,您不需要 python,但我想这样做)

根据我的研究,我相信 Flask 是做这件事的图书馆(?),但我真的不知道该怎么做。我发现的例子很少。如果有人可以实现上面的示例或告诉我如何准确地做到这一点,我将不胜感激。

我知道网上已经有一些关于这个概念的问题,但正如我所说的,例子很少。

Mic*_*uer 9

你说的对 Flask 是一个很好的解决方案,到处都有例子和教程。如果您只想在按下按钮时运行特定功能并在 javascript 中返回某些内容,我在下面提供了一个快速示例。

# app.py
from flask import Flask, render_template
from flask import jsonify

app = Flask(__name__)

# Display your index page
@app.route("/")
def index():
    return render_template('index.html')

# A function to add two numbers
@app.route("/add")
def add():
    a = request.args.get('a')
    b = request.args.get('b')
    return jsonify({"result": a+b})

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80)
Run Code Online (Sandbox Code Playgroud)

然后可以运行它python app.py并确保您的 index.html 在同一目录中。然后您应该可以访问http://127.0.0.1/并查看您的页面加载情况。

这实现了一个将两个数字相加的函数,这可以通过调用http://127.0.0.1/add?a=10&b=20在您的 javascript 中调用。这应该返回{"result": 30}

您可以使用下面的代码在您的 javascript 中获取此代码,并将此代码放置在单击回调的按钮中。

let first = 10;
let second = 20;
fetch('http://127.0.0.1/add?a='+first+'&b='+second)
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log("When I add "+first+" and "+second+" I get: " + myJson.result);
  });

Run Code Online (Sandbox Code Playgroud)

这应该是准系统的基础知识,但是一旦您可以将数据提交到 Flask 并取回数据,您现在就有了一个可以在 Python 中运行的界面。

编辑:完整的前端示例

https://jsfiddle.net/4bv805L6/


Leo*_*oFr 5

我真的很感谢花时间在这个答案上。但答案并没有以我需要的方式帮助我。那时我不知道该怎么做,但从那时起我不久前就弄清楚了,我想我应该在这里分享我的解决方案:

那是app.py:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/stick', methods=['GET', 'POST'])
def stick():
    if request.method == 'POST':
        result = request.form['string1'] + request.form['string2']
        return render_template('index.html', result=result)
    else:   
        return render_template('index.html')

if __name__ == "__main__":
    app.run()
Run Code Online (Sandbox Code Playgroud)

这就是index.html(放入文件夹templates):

<!DOCTYPE html>
<html>
<body>
    <h3> Stick two strings </h3>
    <form action="{{ url_for('stick') }}" method="post">
            <input type="text" name="string1">
            <input type="text" name="string2">
            <input type="submit" value="Go!">
            <p id="result"></p>
    </form>
<script>

document.getElementById("result").innerHTML = "{{result}}"

</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

在终端中,输入python app.py它应该可以工作。