Advertisements
I am trying to learn Flask. and here I am facing an issue.
I have created a route ( /register
) in my Flask app.
and I am trying to trigger this using Postman.
But I am getting this Error:
TypeError: 'ImmutableMultiDict' object is not callable
Here is my code for /register
route.
@app.route('/register', methods=['POST'])
def register():
if request.method == 'POST':
fname = request.form(["fname"])
mname = request.form(["mname"])
lname = request.form(["lname"])
gender = request.form(["gender"])
age = request.form(["age"])
email = request.form(["email"])
password = request.form(["password"])
new_member = User(fname, mname, lname, gender, age, email, password)
try:
db.session.add(new_member)
db.session.commit()
return redirect('/')
except:
return 'Error: Error found'
Here is request body that I am sending from Postman.
{
"fname":"ashutosh",
"mname":"kumar",
"lname":"yadav",
"gender":"m",
"age":25,
"email":"test@gmail.com",
"password": "PassWord@123"
}
But I am getting this Error: TypeError: 'ImmutableMultiDict' object is not callable
In case if it is needed, here is curl request.
curl --location --request POST 'http://127.0.0.1:5000/register' \
--header 'Content-Type: application/json' \
--data-raw '{
"fname":"ashutosh",
"mname":"kumar",
"lname":"yadav",
"gender":"m",
"age":25,
"email":"test@gmail.com",
"password": "PassWord@123"
}'
A similar problem I found on SOF
But I am not able to figure out what issue is there in my code.
Kindly help me guys.
>Solution :
request.form works only if you POST data with the application/x-www-form-urlencoded or multipart/form-data. Since your POST data is JSON , make sure you are using request.json
content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
body = request.json
fname = body["fname"]
mname = body["mname"]
lname = body["lname"]
gender = body["gender"]
age = body["age"]
email = body["email"]
password = body["password"]