首页 > 解决方案 > 从 Flask 服务器运行 python 脚本

问题描述

我需要能够从我的 Flask 服务器上的 HTML 文件运行 Python 脚本。在我的 HTML 页面上,有 3 个输入框和一个ok按钮。当ok按下按钮时,它应该将输入框中的数字传递给命令以运行 python 脚本。需要运行的命令示例是python magicHome-rgb.py <inputBox1> <inputBox2> <inputBox3>,但将 替换为<inputBox[no]>输入框中的输入。

如果这没有意义,请随时询问更多...

有谁知道这是否可能?

标签: pythonhtmlflask

解决方案


不,即使可以,也不要。相反,如果您使用表单来收集数据,请使用 POST 请求将该数据发送到 Flask 服务器并让函数处理它。不要使用单独的脚本。

示例python函数:

@app.route('/your-url', methods=('GET', 'POST'))
    def get_input():
        if request.method == 'POST':
            box1 = request.form['inputbox1']
            box2 = request.form['inputbox2']
            box3 = request.form['inputbox3']

            # -- do stuff --

        return render_template('your_template.html')

可能使用的表单的 HTML 示例:

  <form method="post">
    <input type=number name="inputbox1" id="inputbox1" required/>
    <input type=number name="inputbox2" id="inputbox2" required/>
    <input type=number name="inputbox3" id="inputbox3" required/>
    <input type="submit" value="Ok">
  </form>

在上述情况下,box1box2box3存储您可能需要的 3 个输入框的输出。

或者,要从 HTML 文件运行代码,您还可以使用嵌入在 HTML 文件中的 javascript 处理输入。


推荐阅读