SalamalCamel
SalamalCamel

Reputation: 75

Python Flask POST 400 Bad Request Error

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.

Upvotes: 3

Views: 28003

Answers (3)

mhawke
mhawke

Reputation: 87054

You are not posting JSON in your client and nor is your browser, so don't try to process it as JSON in your server. Just access the values using request.form for POST requests or request.args for GET requests:

@app.route("/", methods=['GET','POST'])
def result():
    if request.method == 'POST':
        data = request.form
    else:
        data = request.args

    temp = data.get('Temp')
    return render_template('main.html', name=temp)

Upvotes: 0

furas
furas

Reputation: 142631

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)

Upvotes: 3

rykener
rykener

Reputation: 761

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>

Upvotes: 4

Related Questions