Python Flask POST 400 Bad Request Error

22,815

Solution 1

If you're just navigating to http://10.0.0.119 then you're sending a GET request to def result() which will result in a bad request because there is no data['Temp']

In order to make this work in a browser you will need to send a POST request from the app itself, and then have a way to view it.

Your app could be:

import requests
from random import randint

from flask import Flask, request, render_template


app = Flask(__name__)

def Temp():
  return randint(0,20)

@app.route("/", methods=['GET','POST'])
def result():
    if request.method == 'POST':
        data = request.form.get('data')
        Temp = data['Temp']
        return render_template('dispaly_data.html', name=Temp)
    else:
        data = {'Temp': Temp()}
        return render_template('post_data.html', data=data)


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

And your form in post_data.html could be something like:

<form action="/" method='post'>
    <input type="hidden" name="data" value="{{ data }}"/>
    <input type='submit' value='Send Post'>
</form>

Solution 2

You send wrong request. You have to use json=data to send it as JSON

r = requests.post('http://10.0.0.119', json=data)
Share:
22,815
SalamalCamel
Author by

SalamalCamel

Updated on July 09, 2022

Comments

  • SalamalCamel
    SalamalCamel almost 2 years

    I'm trying to POST data to a website using flask, when I try to return the data I get a 400 Bad Request error.

    Here is my python code that sends the POST request:

    import requests
    from random import randint
    
    def Temp():
    return randint(0,20)
    
    
    data = {'windspeed':WindSpeed(), 'Temp': Temp(), 'WindDir':WindDir()}
    r = requests.post('http://10.0.0.119', data = data)
    print (r.text)
    

    And this is the server code:

    from flask import Flask, request, render_template
    
    
    app = Flask(__name__)
    
    @app.route("/", methods=['GET','POST'])
    def result():
        data = request.get_json(force=True)
        Temp = data['Temp']
        return render_template('main.html', name=Temp)
    
    if __name__ == "__main__":
    app.run()
    

    This returns a 400 error when run in a a browser, but the client script gets the correct respone:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>Temperature</h1>
    <p>15</p>
    
    </body>
    </html>
    

    Where 15 is the data['Temp'] variable.