使Flask服务器与jQuery通信

时间:2018-11-16 20:25:25

标签: python jquery flask

这是我的jquery代码:

<script>

    window.setInterval(function () {
        /// call your function here
        $("#productmicro").html("KO");
        var request = $.ajax({
            url: "http://54.66.92.666:1666/status",
            type: "POST",
            crossDomain: true,
            data: {STATUS: 'ISOK?'},
            dataType: "json",
            success: function (jsonData) {
                console.log(jsonData);
                $("productmicro").html(jsonData["STATUS"]);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
                $("#productmicro").html(errorThrown);

            }
        });
    }, 5000);
</script>

这是我的烧瓶部分:

from flask import Flask
from flask import request
from flask import jsonify
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})

@app.route("/status", methods=["post"])
def status():
    try:
        data = request.data
        document = json.loads(data.decode("utf-8"))
        result_data = {}
        if document["STATUS"] == "ISOK?":
            result_data["STATUS"] = "OK"
        else :
            result_data["STATUS"] = "OK"
        return jsonify(result_data)
    except Exception as e:
        return jsonify(
            {
                "STATUS": "KO",
                "EXCEPTION": PrintException() + " " + str(e),
                "DOCUMENT": document,
                "ORIGIN": "ProductMicro",
            }
        )

@app.after_request
def after_request(response):
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Headers", "Content-Type,Authorization")
    response.headers.add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS")
    return response


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=81666)

如何使两者交流?

此方法出现内部服务器错误。

但是我已经尝试过

  

document = request.get_json()

在烧瓶部分 但是我有这样的错误

  

document = None

所以,如果有人对如何使此jquery脚本和flask通信有任何想法

致谢

0 个答案:

没有答案