Home > OS >  Flask Get Request for JSON
Flask Get Request for JSON

Time:01-27

I am trying to make an Intranet of Things (IoT) page. I am using Flask for the python backend. I am trying to update the state of my light in real time. I believe the route to go is the AJAX/XMLHttpRequest on the front end. I am struggling to figure out how to send the JSON to the front end from the back end. Every example online seems to be a POST request instead of Get.

I believe I have the object created correctly as well as open and sending it correctly. I think my error is on the python side and not doing request right. I tried copying this example https://gist.github.com/KentaYamada/2eed4af1f6b2adac5cc7c9063acf8720. All the other stack overflow examples seem to do different methods like return or add an if statement for the return. I am not sure example how to setup to return the 'get' argument in request.args.get[]. The suggested potential duplicates only show one end, are in express js with the $ syntax which I'm not familiar with, or something similar

I am currently getting 500 errors. Below is my code.

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 >
    <img src="{{light}}" id="light" onclick="Power(this)" />
    <figcaption id = light1 >Light</figcaption>
    </figure>


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

    <figure >
    <img src="{{temp}}" id="temp" onclick="Power(this)" />
    <figcaption id = temperature >{{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? as well as looked at the APIs

CodePudding user response:

You can create different routes for html and for json.

For your Json try something like below

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

for html you can use your home() function that you’ve already created

Assume your response is : { "state" : "Ok" }

This is what you're Javascript should look like:

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

This should work. It's pretty straight forward.

  • Related