Why is the Flask 'POST' method not working?

Question:

I’m trying to create a small chatting platofrm on Flask. Nothing fancy, just an experiment. My problem is that flask doesn’t seem to be taking any input from my post statements, even though I get the message in the console.

text = {"text":typed}             #both userenter and typed are strings
username = {"username":userenter}
requests.post(send_url, username)   
requests.post(send_url, text)
typed = ''

That’s the most important part of the client code, as the rest is mainly getting things printed and getting keystrokes.

This is the flask code:

chat = {"Chat":["Welcome to my chatting thing!n"]}
@app.route('/chat', methods = ['POST'])
def chatt():
    global chat
    username = request.form['username']
    Text = request.form['text']
    chat["Chat"].append(username)
    chat["Chat"].append(": ")
    chat["Chat"].append(Text)
    chat["Chat"].append("n")
    return

For the flask code, my main goal is to take the input from the post and append it to the list within the dictionary ‘chat’

Console logs:

172.31.128.1 - - [16/Feb/2023 23:07:42] "GET /get-chat HTTP/1.1" 200 -
172.31.128.1 - - [16/Feb/2023 23:07:43] "GET /get-chat HTTP/1.1" 200 -
172.31.128.1 - - [16/Feb/2023 23:07:44] "GET /get-chat HTTP/1.1" 200 -
172.31.128.1 - - [16/Feb/2023 23:07:45] "POST /chat HTTP/1.1" 400 -
172.31.128.1 - - [16/Feb/2023 23:07:45] "POST /chat HTTP/1.1" 400 -
172.31.128.1 - - [16/Feb/2023 23:07:46] "GET /get-chat HTTP/1.1" 200 -
172.31.128.1 - - [16/Feb/2023 23:07:47] "GET /get-chat HTTP/1.1" 200 -
172.31.128.1 - - [16/Feb/2023 23:07:48] "GET /get-chat HTTP/1.1" 200 -
172.31.128.1 - - [16/Feb/2023 23:07:49] "GET /get-chat HTTP/1.1" 200 -

The console does register that the posts got through, but nothing was added to the list.

I’ve tried playing around with the code and trying out different syntaxes, as well as printing it out. However, no matter what I’ve tried, it feels like the console is the only proof that the POST statements went through.

Edit #1:
I have tried using debuggers such as breakpoint() and some others. Didn’t work.
Also, somebody pointed out that my post was returning 400 instead of 200, which is a malformed request. If anybody knows a solution to that, please tell me.

Tell me if you need any more information about my code if you need it.

Asked By: Shadowy_Coder

||

Answers:

  1. There is 400 error, check what that means

  2. You’re sending two requests instead of one. Your action is expecting 2 parameters:

    data = {"text": typed, "username": userenter}             
    requests.post(send_url, data)
    

You may also want to receive some response, so action can return something that you can pick up.

Answered By: iurii_n
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.