Home > Blockchain >  Why is my Flask server returning a 400 error?
Why is my Flask server returning a 400 error?

Time:04-18

Does anyone have any idea why a PATCH request to my flask server would return a 400 error? I'm sending json data. The POST request works fine.

Thanks in advance!

@app.route('/pokedex/add/', methods=["POST", "PATCH"])
def add_pokemon():
    conn = get_db_connection()
    cur = conn.cursor()
    if request.method =='PATCH':
        try:
            cur.execute("UPDATE pokedex_mon SET caught = True WHERE name="   request.json['name'])
            conn.commit()
            cur.close()
            conn.close()
            return jsonify(True)
        except:
            return jsonify(False)
    else:
        if (request.json['caught'] == True):
            caught = True
        else:
            caught = False
        try:
            cur.execute('INSERT INTO pokedex_mon (name,description,image,seen,caught) VALUES (%s,%s,%s,%s,%s)', (request.json['name'], request.json['description'], request.json['image'], True, caught))
            conn.commit()
            cur.close()
            conn.close()
            return jsonify(True)
        except:
            return jsonify(False)

CodePudding user response:

I think you are over writing the default 'GET' method in @app.route . Write 'GET' also with 'POST' and 'PATCH'. I am not sure but it might be the problem.

CodePudding user response:

You didn't give the stacktrace. I guess that this line caused an error:

cur.execute("UPDATE pokedex_mon SET caught = True WHERE name="   request.json['name'])

Suppose request.json['name'] equals test, then your sql will be UPDATE pokedex_mon SET caught = True WHERE name=test.

name=test is wrong, it should be name='test'.

By the way, you'd better not concat sql parameters by hand, the best practice is to use parameterized queries.

  • Related