Search code examples
pythonjsonmongodbputflask-restful

Flask Restful PUT update list with object


I want to use Flask Restful to update a list with an object using a PUT request.

The resulting JSON should look like:

{"EmployeeID":"12345", "firstname":"Joe","lastname":"Bloggs","SupervisorName":"Name","SupervisorID":"2468","role":"Role","active":"True","hours":["{'date':'01/01/2017','qty':'3','project':'Project 1'}"]"}

The Hours field in the JSON is a list. The aim is to append an object to the list on each PUT request.

The Parser for hours is:

parser.add_argument('hours', action='append')

The Put method code is:

    def put(self, EmployeeID=None):
        data = parser.parse_args()
        if not data:
            data = {'ERROR': 'No Data'}
            return jsonify(data)
        else:
            if EmployeeID:
                if mongo.db.employee.find_one({'EmployeeID': EmployeeID}):
                    mongo.db.employee.update_one({'EmployeeID': EmployeeID}, {set: {"hours": data.get('hours')}})
                    return {'response': 'Employee:'+str(EmployeeID)+' updated'}
                else:
                    return {'Error': 'employee ' + str(EmployeeID) + ' not found'}

            else:
                return {'response': 'Employee ID missing'}

Is the update_one method the right one to use here?

using curl PUT request :

 curl -H "Content-type: application/json" -X PUT -d '{"EmployeeID":"1234",...,"hours":{'time':'','qty':'3','project':'Project 1'}}' http://127.0.0.1:5000/api/people/1234

Gave the error:

{
 "message": "Failed to decode JSON object: Expecting property name enclosed in double quotes: line 1 column 168 (char 167)"
}

But When I add the quotations into the request it return an error:

 {
 "message": "Failed to decode JSON object: Unterminated string starting at: line 1 column 167 (char 166)"
}

I can't figure out whether there is an issue with the requests or with the actual Flask-Restful code.

What is the correct way to go about updating a Mongo document list with an object?


Solution

  • If anyone runs into this issue I finally got there.

    I had to change the RequestParser:

    parser.add_argument('hours')
    

    Removing the action='append'

    Then using the mongo update:

    mongo.db.employee.update_one({'EmployeeID': EmployeeID}, {'$addToSet': {"hours": data.get('hours')}})