0

No matter what I do I keep getting AttributeError: 'str' object has no attribute 'read'. I think it has to do with my variable ajax_data, so I made some attempts to try to fix it. Here are some attempts I have made to solve this error:

ajax_data = json.load(request.data.read().decode('utf-8')) 
ajax_data = json.loads(request.data.read().decode('utf-8'))
ajax_data = json.loads(request.data.read())
ajax_data = json.load(request.data.read())
ajax_data = json.load(request.data.decode())
ajax_data = json.loads(request.data.decode())

Here is my code:

@portfolio_app.route('/postContactForm', methods=['POST'])
def postContactForm():
    #Gets the data sent from frontend  
    ajax_data = json.load(request.data.decode()) 
    print(ajax_data)

    # Connect to DB
    db = connectToDB()

    #Choose collection name
    contact_data = db.contact_data
    print(contact_data)

    #Inserts data into database
    contact_data.insert_one(ajax_data)

    #Returns data to ajax
    return jsonify({'Success it worked'})
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
kvothe
  • 3
  • 3

1 Answers1

1

You should change this:

request.data.read()

into this:

request.data

request.data is already a string, there's no point "reading" it.


trying to answer the question in the comments. instead of ajax_data = json.load(request.data) you should use something like this:

try :
    ajax_data = json.loads(request.data)  # notice: loadS here
except :
    print( 'Invalid JSON data', request.data )
lenik
  • 23,228
  • 4
  • 34
  • 43