-1

I want to send some POST data to a flask webpage then have it display that data but when I try to send the data {"hi": "hi"} it gives me these errors:

code 400, message Bad request syntax ('hi=hi') "None / HTTP/0.9" HTTPStatus.BAD_REQUEST -

my code is this:

from flask import Flask, request

app = Flask("__name__")

@app.route("/", methods=['GET', 'POST'])
def hi():
    return "hi"
    if request.method == "POST":
        data = request.values
        return f"<p>{data}</p>"

the flask app:

and the post data sending program:

import requests

requests.post('http://127.0.0.1:5000', data={ "req": "hi" })

am I just not understanding POST requests right or am I doing something really wrong?

1 Answers1

0

please see this answer regarding how to access the request's data.

the requests.post you are using as http client is sending the data as form-encoded, so we could use Flasks' request.form to access the data. Also your function needs some restructuring, else it will always return "hi", we can make it:

from flask import Flask, request

app = Flask("__name__")

@app.route("/", methods=['GET', 'POST'])
def hi():
    if request.method == "GET":
        return "hi"
    if request.method == "POST":
        # data = request.values
        # data will be = req if your POST request has req field, else will be = field: req was not provided
        data = request.form.get("req", "field: req was not provided")
        return f"<p>{data}</p>"

if you dont know the fields the POST request will contain, you can use this loop to get the fields and their values:

@app.route("/", methods=['GET', 'POST'])
def hi():
    if request.method == "GET":
        return "hi"
    if request.method == "POST":
        # data = request.values
        for field in request.form:
            print(field, request.form.get(field))
        return "hi"
ilias-sp
  • 6,135
  • 4
  • 28
  • 41