Flask 请求出现问题 - returns GET 在任何操作之前

Trouble with Flask Requests - returns GET before any actions

现在,我正在开发一个简单的应用程序,它只显示用户输入的内容。我有一个标准的 Flask 布局,如下所示:

/flaskTest
  main.py
  /static
    script.js
  /templates
    calculation.html

我正在开发一个应用程序,它将用户创建的图表解析为 JSON,将 JSON 发送到 python 文件以处理成绘图,并且发回将出现在网页上的该图的图像。我已经完成了大部分工作,但由于我是 Web 开发的新手,所以在集成客户端和服务器端组件时遇到了很多麻烦。

我正在尝试使用 jQuery 和 Flask 来执行此操作,但我不断收到回复说 calculation() 是使用 GET 而不是 POST 调用的,我不知道为什么.这是我的代码:

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/", methods=['GET','POST'])
def calculation():
    result = ''
    error = ''
    if request.method=='POST':
        result = request.data
    else:
        error= request.method
    return render_template('calculation.html', result=result, error=error)

if __name__ == "__main__":
    app.run(debug=True)

calculation.html

<!DOCTYPE html>
<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="../static/script.js"></script>
</script>
</head>

<body>
<h1>Calculation</h1>
<form>
    <input id="userInput" value="">
</form>
<button id="submit">Submit</button>
    {% if result %}
    <p>
        <label name='result'>Result: {{ result }}</label>
    </p>
    {% endif %}
    {% if error %}
    <p>
    <label name="error">{{ error }}</label>
    </p>
    {% endif %}
</body>
</html>

script.js

$(document).ready(function(){
    $("#submit").click(function(){
        userInput = $("#userInput").val();
        $.post("main.py",userInput);
    });
});

我知道对于我正在完成的简单任务,将整个事情作为一个表单来完成可能会更容易,但我的最终项目将没有表单 - 只有一个 canvas 用户可以在其中创建图表和提交要处理的图表的按钮,因此我想保持此实现不变。

变化:

$.post("main.py",userInput);

$.post("/",userInput);

该参数应该是 URL 而不是文件。

还应注意,这不会更新页面上的任何内容。如果你想更新一些东西,你将不得不编写一些 JS 来处理来自你的 Flask 应用程序的响应。另外看看你的 calculation() 视图的构建方式我不确定 AJAX 是你想要使用的。

更新:由于您希望它是异步的,因此您将不得不进行一些更改:

main.py

import json
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

@app.route("/", methods=['GET','POST'])
def calculation():
    if request.method=='POST':
        results = json.loads(request.data)
        # do stuff to result here
        # you will need to pass a dictionary back into jsonify()
        return jsonify(results)
    return render_template('calculation.html')

if __name__ == "__main__":
    app.run(debug=True)

您需要创建一个新字典以传递回 jsonify(),因此请执行您需要的任何计算并从中创建一个新字典。我的建议是为此创建一个单独的函数并像这样保存结果:

def some_calculation(a_dict):
    # MATH!
    return {'new_key': a_number}

然后在您看来:

response = some_calculation(result)
return jsonify(response)

我从你的模板中删除了多余的代码:

calculation.html

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="../static/script.js"></script>
    </head>
    <body>
        <h1>Calculation</h1>
        <input id="userInput" value="" name="userInput">
        <button id="submit">Submit</button>
        <ul id="results">
        </ul>
    </body>
</html>

JSON 响应将附加到新的 <ul>

script.js

$(document).ready(function(){
    $("#submit").click(function(){
        userInput = $("#userInput").val();
        $.ajax({
          type: "POST",
          url: '/',
          data: JSON.stringify({input: userInput}),
          contentType: 'application/json;charset=UTF-8',
          success: function(response){
            // console.log(response);
            $("#results").append("<li>" + response.input + "</li>");
          },
        });
    });
});

我更喜欢使用长格式 $.ajax() 方法,但可以随意使用 post()。请注意,在您的应用程序中,您可能必须将 response.input 更改为 response.whatever_your_new_key_is。我只是在我的示例中返回相同的 JSON 对象,所以我使用了我发送到服务器的相同密钥。如果您需要查看 response 对象中的内容,您可以取消对 console.log() 行的注释并对其进行更多更改。因此,如果您的新字典看起来像 {"answer": 42},您可以将其更改为 response.answer