Issue
I am trying to create a project where a particular structure is followed for input.I started my project on flask and when the POST method is applied to it and an item is requested from an input it is showing an error.
This is the structure of input i gave in my POST method of the POSTMAN:
{
"name": "Fruits and Milk",
"items": [{"name": "milk", "value": 50, "paid_by": [{"A": 40, "B": 10}], "owed_by": [{"A": 20,"B": 20, "C": 10}]},
{"name": "fruits", "value": 50, "paid_by": [{"A": 50}], "owed_by": [{"A": 10,"B": 30, "C": 10}]}]
}
My flask code is :
from flask import Flask,jsonify
app = Flask(__name__)
@app.route("/expenses/<string:group_name>/add", methods = ["POST"])
def add_expenses(group_name):
"""
Add new expense to group.
"""
data = request.form
"""
Code block gets the List of all members in expense.
"""
members = []
for item in data["items"]:
for member in item['paid_by'][0]:
members.append(member)
for member in item['owed_by'][0]:
members.append(member)
"""
Code block checks if Group, expense exists.
If expense with same name doesn't exists add new expense to group.
Update the members of the group.
"""
for group in groups:
if group.name == group_name:
for expense in group.expenses:
if expense['name'] == data['name']:
return {"msg": "Expense with name already exists"}
group.add_expense(data)
group.set_members(set(members))
return {"method ": "Expense added successfully"}
return {"method ": "Group does not exist"}
if __name__=="__main__":
app.run(debug=True)
When i run this code i get an error of:
File "/home/black_knight/Documents/Expense Tracker/FLaskProject/project.py", in add_expenses
for item in data["items"]:
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'items'
I have added the photo of the POSTMAN input:
Solution
You're having a key error because "items" isn't a key in the dictionary returned by request.form. Check if your contenttype value in the headers is set to receive data via form. If you're receiving via json then you should use request.json
or request.get_json(force=True)
to force json values irrespective of the contenttype.
Answered By - Mazimia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.