簡體   English   中英

Flask 獲取 JSON 請求

[英]Flask Get Request for JSON

我正在嘗試制作 Intr.net of Things (IoT) 頁面。 我正在為 python 后端使用 Flask。 我正在嘗試實時更新我的燈的 state。 我相信到 go 的路由是前端的 AJAX/XMLHttpRequest。 我正在努力弄清楚如何將 JSON 從后端發送到前端。 網上的每一個例子好像都是POST請求而不是Get。

我相信我已正確創建 object 並正確打開和發送它。 我認為我的錯誤是在 python 方面並且沒有正確執行請求。 我試着復制這個例子https://gist.github.com/KentaYamada/2eed4af1f6b2adac5cc7c9063acf8720 所有其他堆棧溢出示例似乎都執行不同的方法,例如返回或為返回添加 if 語句。 我不確定示例如何設置以返回 request.args.get[] 中的“get”參數。 建議的潛在重復項僅顯示一端,在 express js 中使用我不熟悉的 $ 語法,或類似的東西

我目前收到 500 個錯誤。 下面是我的代碼。

HTML:

<html> <head>
    <meta name = "Viewport" context = "width=device-width. initial-scale=1.0">
    <title>Chang's IoT Controls</title>
    <link href="{{url_for('static',filename='Styles/Controls.css')}}" rel="stylesheet" type="text/css"/>
    </head>

    <body>
        <h1>Controls</h1>
        <p> Controls to control Chang's IoT Hub</p>

    <figure class="item">
    <img src="{{light}}" id="light" onclick="Power(this)" />
    <figcaption id = light1 class="caption">Light</figcaption>
    </figure>


    <figure class="item">
    <img src="{{url_for('static',filename='Images/OffLight.jpg')}}" id="temp" onclick="Power(this)" />
    <figcaption class="Temperature" id="state" <span style="border:2px solid black">Here</span></figcaption>
        <button type = "button" id="toggle" onclick ="Power(this)" > Change Lights </button>
    </figure>

    <figure class="item">
    <img src="{{temp}}" id="temp" onclick="Power(this)" />
    <figcaption id = temperature class="caption">{{degree}}</figcaption>
    </figure>


    <script>
    document.getElementById("state").innerHTML = "reached";

    const xhttp = new XMLHttpRequest();
    xhttp.onload = function () {
        const xmlDoc = JSON.parse(this.responseText);
        const status = xmlDoc.Status;
        document.getElementById("state").innerHTML = status;

        if(status == "On")
        {
            document.getElementById("temp").src = "{{url_for('static',filename='Images/OnLight.jpg')}}";
        }
        if(status == "Off")
        {
            document.getElementById("temp").src = "{{url_for('static',filename='Images/OffLight.jpg')}}";
        }
    }
    xhttp.open("GET",'/get_json');
    xhttp.send();
    console.log(xhttp.response);
    </script>

    <p>
        <a href="/">Homepage</a>
    </p>

    </body>

</html>


Python:

from flask import Flask, redirect, url_for, render_template, request

app = Flask(__name__)

@app.route("/", methods=["POST", "GET"])
def home():
    imgname = url_for('static', filename='Images/OnLight.jpg')
    thermo = url_for('static', filename='Images/Thermometer.png')
    heat = 50

#    if request.method == "GET":
#        file = request.form(url_for('static',filename='test.json'))
#        return file

    return render_template("Controls.html", light=imgname, temp=thermo, degree=heat)

@app.route('/get_json')
def get_json():
    return jsonify(Status= "On")

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

JSON:

{
  "Light":
  [{"Status": "On"}]


}

I tried looking at examples including git repos like https://gist.github.com/KentaYamada/2eed4af1f6b2adac5cc7c9063acf8720 as well as stack overflow pages like Getting data from xhr request using python and how to properly get data from javascript to my python flask backend using XMLHttpRequest? 以及查看 API

您可以為 html 和 json 創建不同的路由。

對於您的 Json,請嘗試以下操作

@app.route(“/get_json“, methods = [“GET”])
def get_json_to_frontend():
    // logic
    return jsonify( your response) 

對於 html 你可以使用你已經創建的 home() function

假設您的回答是:{ "state": "Ok" }

這就是你的 Javascript 應該是這樣的:

let xhttp = new XMLHttpRequest();
        xhttp.onload = () => {
            let t = JSON.parse(xhttp.response);
            console.log(t.state);
        }
        xhttp.open("GET", URL);
        xhttp.send();

這應該工作。 這很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM