def _serialize_data(self, data, serializer_class=None):
"""
Function to serialize data with the serializer given in the
serializer_class attribute. Also validates the data and responds with
a HTTP_400_BAD_REQUEST when validation failed. Due to being an open
api we do not want to give away the required fields and their
requirements.
Args:
data(dict): Dictonary with that data that need to be serialized.
serializer_class(Serializer): Class to use for serialization.
Returns:
dict: Dictionary with the validated data.
Raises:
NotImplementedError: When serializer_class attribute is not set.
ParseError: When validation fails but because it's an open API we
do not want to give away what failed. ParseError returns a
HTTP_400_BAD_REQUEST.
"""
if serializer_class is None:
if self.serializer_class is None:
raise NotImplementedError('serializer_class Attribute should be set')
else:
self.serializer_class = serializer_class
serializer = self.serializer_class(data=data)
if not serializer.is_valid(raise_exception=False):
# Log errors.
logger.info('BAD REQUEST! Serialization failed with following errors:\n\n{0}\n\nData:\n\n{1}'.format(
serializer.errors,
data,
))
# This raises a bad request response.
raise ParseError(detail=None)
return serializer.validated_data
评论列表
文章目录