Failed to decode JSON object when calling GET request with Flask Python

1

I try to send a GET request after sending a message to a server, but I receive an error. I think it's because

@app.route('/chat',methods=["POST"])
def chat():
    try:
        user_message = request.form["text"]
        response = requests.post('http://localhost:5005/conversations/default/respond', data={"q":user_message})
        response = response.json()
        print("response :\n",response) 

Here is the error Let me know if you need the full crawl.

2018-06-06 13:39:21+0100 [-] "127.0.0.1" - - 
[06/Jun/2018:12:39:21 +0000] "POST /conversations/default/respond HTTP/1.1" 500 11082 "-" "python-requests/2.18.4"
2018-06-06 13:42:53+0100 [-] 2018-06-06 13:42:53 
ERROR    __main__  - Failed to decode json during respond request. 
Error: Expecting value: line 1 column 1 (char 0). Request content: 'b'q=Hi''

It really works fine with the terminal:

mike@mike-thinks:~/Programing/Rasa/myflaskapp$ curl -XPOST localhost:5005/conversations/default/respond -d '{"query":"Hello"}'
[{"recipient_id": "default", "text": "Hello! How can I help?"}]

Update

@app.route('/chat',methods=["POST"])
def chat():
    try:
        user_message = request.values.get("text")
        response = requests.post('http://localhost:5005/conversations/default/respond', json={"key":user_message})

Da:

'Response' object has no attribute 'get' 127.0.0.1 - - [06 / Jun / 2018 14:28:30] "POST / HTTP / 1.1 chat" 200 -

OS Version Linux 16.04 Flask 1.0.2
Flask-MySQLdb 0.2.0
Flask-WTF 0.14.2

    
asked by ThePassenger 06.06.2018 в 14:53
source

1 answer

2

As fedorqui has noticed, use request.values.get('text') instead of request.form['text']

@app.route('/chat',methods=["POST"])
def chat():
    try:
        user_message = request.values.get("text")
        response = requests.post('http://localhost:5005/conversations/default/respond', json={"query":user_message})
        response = response.json()
        print("response :\n",response) 
        response_text = response
        return jsonify(response[0])

Because I think it's because of the nature of the object that the request returns. Anyway, according to user1807534 :

if you want to recover POST data,

user_message = request.form.get("text")

if you want to retrieve GET data (query string),

user_message = request.args.get("text")

Or if you do not care / know if the value is in the query string or in the publication data,

user_message = request.values.get("text"). 

request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.

However , this will not appear in the Flask application

    
answered by 06.06.2018 / 16:48
source