def post(self, request, format=None): """ Method used to create a new Person object. The object data is provided in a serialized format. @param request: HttpRequest used to provide person data. @type request: HttpRequest @param format: The format used for object serialization. @type format: string @return: HttpResponse containing the id of the new Person object, error otherwise. @rtype: HttpResponse """ logger.debug('Creating a new Person object') # look for an already existing person with the same name person = find_person(request.data["first_name"], request.data["last_name"]) if person is not None and len(person) > 0: logger.debug('Returned Person object ' + str(person[0].id) + ' - ' + person[0].first_name + ' ' + person[0].last_name) return Response(PersonSerializer(person[0]).data, status=status.HTTP_201_CREATED) # if the person doesn't exist create a new one serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() logger.debug('Created a new Person object') return Response(serializer.data, status=status.HTTP_201_CREATED) logger.error('Error on Person object creation') return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, pk, format=None): """ Method used to update a Person object data, providing all fresh data in a serialized form. @param request: HttpRequest containing the updated Person field data. @type request: HttpRequest @param pk: Person primary key, used to retrieve object data. @type pk: int @param format: Format used for data serialization. @type format: string @return: HttpResponse containing the Person object updated data, None in case of error @rtype: HttpResponse """ with edit_lock: # check if there is already a person with the same name if 'first_name' in request.data and 'last_name' in request.data: person = find_person(request.data["first_name"], request.data["last_name"]) if person is not None and len(person) > 0: logger.debug('Updated data on Person object ' + str(person[0].id) + ' - ' + person[0].first_name + ' ' + person[0].last_name) return Response(PersonSerializer(person[0]).data, status=status.HTTP_200_OK) # otherwise edit and return the current object person = self.get_object(pk) serializer = PersonSerializer(person, data=request.data, partial=True) if serializer.is_valid(): serializer.save() logger.debug('Person object ' + str(pk) + ' successfully updated') return Response(serializer.data) logger.error('Provided data not valid for Person object ' + str(pk)) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)