Beispiel #1
0
 def get_paginated_response(self, data):
     response_status = status.HTTP_200_OK
     response_data = generate_formatted_response(status=True, payload={'users': data})
     response_data['next'] = self.get_next_link()
     response_data['prev'] = self.get_previous_link()
     response_data['count'] = self.page.paginator.count
     return Response(response_data, status=response_status)
Beispiel #2
0
    def post(self, request, *args, **kwargs):
        try:
            serializer = self.get_serializer(data=request.data)

            if serializer.is_valid():
                user = serializer.object.get('user') or request.user
                token = serializer.object.get('token')
                if user and token:
                    user_instance = modify_user_response(
                        UserLoginSerializer(user).instance.__dict__)
                    response_status = status.HTTP_200_OK
                    payload = {'user': user_instance, 'token': token}
                    response_data = generate_formatted_response(
                        status=True, payload=payload)
                else:
                    raise Exception(serializer.object.get('message'),
                                    status.HTTP_401_UNAUTHORIZED)
            else:
                raise Exception('Mandatory fields are missed!',
                                status.HTTP_400_BAD_REQUEST)
        except Exception as error:
            if error.args: error.message, error.status = error.args
            response_data, response_status = error_handler.get_response_data_and_status(
                error)

        return Response(response_data, status=response_status)
Beispiel #3
0
 def get(self, request, *args, **kwargs):
     try:
         file_pk = int(kwargs['pk'])
         serializer = self.serializer_class(self.get_object(file_pk))
         response_status = status.HTTP_200_OK
         response_data = generate_formatted_response(
             status=True, payload={'file': serializer.data})
     except Exception as error:
         response_data, response_status = error_handler.get_response_data_and_status(
             error)
     return Response(response_data, status=response_status)
    def get_response_data_and_status(error=None):
        # TODO logger
        print(f'ERROR: {type(error)}')

        payload = error.message if hasattr(error, 'message') else str(
            type(error))
        response_status = error.status if hasattr(
            error, 'status') else status.HTTP_400_BAD_REQUEST
        response_data = generate_formatted_response(
            status=False, payload={"message": payload})

        return response_data, response_status
Beispiel #5
0
 def post(self, request, *args, **kwargs):
     try:
         mandatory_fields = {'password', 'first_name', 'last_name', 'email'}
         validation_status, validation_result = validate_mandatory_fields(
             request.data, fields=mandatory_fields)
         if validation_status:
             user = self.create(request, *args, **kwargs)
             response_data = generate_formatted_response(
                 status=True, payload={"user": user.data})
             response_status = status.HTTP_201_CREATED
         else:
             raise Exception(validation_result)
     except Exception as error:
         if error.args: error.message = error.args
         response_data, response_status = error_handler.get_response_data_and_status(
             error)
     return Response(response_data, status=response_status)
Beispiel #6
0
    def get(request, uuid):
        try:
            user = User.objects.get(verification_uuid=uuid, is_verified=False)
            user.is_verified = True
            user.save()
            response_status = status.HTTP_200_OK
            response_data = generate_formatted_response(status=True,
                                                        payload={})
        except User.DoesNotExist as error:
            error.message = "User does not exist or is already verified"
            error.status = status.HTTP_404_NOT_FOUND
            response_data, response_status = error_handler.get_response_data_and_status(
                error)
        except Exception as error:
            response_data, response_status = error_handler.get_response_data_and_status(
                error)

        return Response(response_data, status=response_status)
Beispiel #7
0
    def patch(self, request, *args, **kwargs):
        try:
            user_pk = request.user.pk
            user_instance = self.get_object(user_pk)
            user_avatar = request.data.get('avatar', None)
            if user_avatar and user_avatar.size <= IMAGE_MAX_SIZE:
                filename, ext = f'{datetime.now().timestamp()}', 'png'
                avatar_rel_path = f'{user_pk}/{filename}.{ext}'
                avatar_abs_path = f'{MEDIA_ROOT}/{avatar_rel_path}'
                thumb_rel_path = f'{user_pk}/{filename}_thumb.{ext}'
                thumb_abs_path = f'{MEDIA_ROOT}/{thumb_rel_path}'

                is_exist_or_save_file(user_pk, avatar_abs_path, user_avatar)
                save_thumbnail.delay(user_pk, thumb_abs_path, avatar_abs_path)
                serializer_data = {
                    "avatar": avatar_rel_path,
                    "thumbnail": thumb_rel_path
                }

                serializer = UserSerializer(user_instance,
                                            data=serializer_data,
                                            partial=True)
                serializer.is_valid(raise_exception=True)
                serializer.save()
                user_data = serializer.data
            elif user_avatar.size > IMAGE_MAX_SIZE:
                raise Exception(
                    f"Image is bigger than {IMAGE_MAX_SIZE_NUMBER} MB!")
            else:
                user_data = UserSerializer(user_instance).data
            response_status = status.HTTP_200_OK
            response_data = generate_formatted_response(
                status=True, payload={'user': user_data})

        except (ObjectDoesNotExist, ValueError) as error:
            error.message = "This user doesn't exists!"
            error.status = status.HTTP_404_NOT_FOUND
            response_data, response_status = error_handler.get_response_data_and_status(
                error)
        except Exception as error:
            if error.args: error.message = error.args[0]
            response_data, response_status = error_handler.get_response_data_and_status(
                error)
        return Response(response_data, status=response_status)
Beispiel #8
0
 def delete(self, request, *args, **kwargs):
     try:
         file_pk = int(kwargs['pk'])
         file_instance = self.get_object(file_pk)
         if file_instance and self.get_object(file_pk):
             file_instance.delete()
             response_status = status.HTTP_200_OK
             response_data = generate_formatted_response(
                 status=True, payload={'message': 'Success removed!'})
         else:
             raise Exception()
     except ObjectDoesNotExist as error:
         error.message = "File doesn't exists!"
         error.status = status.HTTP_403_FORBIDDEN
         response_data, response_status = error_handler.get_response_data_and_status(
             error)
     except Exception as error:
         response_data, response_status = error_handler.get_response_data_and_status(
             error)
     return Response(response_data, status=response_status)
Beispiel #9
0
    def get(self, request, *args, **kwargs):
        try:
            user_pk = int(
                kwargs['pk']) if kwargs.get('pk') else request.user.pk
            user_instance = self.get_object(user_pk)
            serializer = self.serializer_class(user_instance)

            response_status = status.HTTP_200_OK
            response_data = generate_formatted_response(
                status=True, payload={'user': serializer.data})
        except (ObjectDoesNotExist, ValueError) as error:
            error.message = "This user doesn't exists!"
            error.status = status.HTTP_404_NOT_FOUND
            response_data, response_status = error_handler.get_response_data_and_status(
                error)
        except Exception as error:
            response_data, response_status = error_handler.get_response_data_and_status(
                error)

        return Response(response_data, status=response_status)
Beispiel #10
0
    def post(self, request, *args, **kwargs):
        try:
            user = request.user
            request_data = eval(json.dumps(request.POST))
            new_file = request.data.get('file')
            if new_file and new_file.size <= FILE_MAX_SIZE:
                filename, ext = str(new_file).rsplit(".", 1)
                title = request_data.get('title', filename)
                user_files = [item.title for item in user.files.all()]
                if title not in user_files:
                    filename += f'_{datetime.now().timestamp()}'
                    file_rel_path = f'{user.pk}/{filename}.{ext}'
                    file_abs_path = f'{MEDIA_ROOT}/{file_rel_path}'
                    request_data['file'] = file_rel_path
                    request_data['owner'] = request.user.pk

                    is_exist_or_save_file(user.pk, file_abs_path, new_file)

                    serializer = self.serializer_class(data=request_data,
                                                       partial=True)
                    if serializer.is_valid():
                        serializer.save()
                    response_status = status.HTTP_200_OK
                    response_data = generate_formatted_response(
                        status=True, payload={'file': serializer.data})
                else:
                    raise Exception(
                        "You have the file with this title already! Rename it please."
                    )
            else:
                raise Exception(
                    f"Please import file with size smaller than {FILE_MAX_SIZE_NUMBER} GB!"
                )
        except Exception as error:
            if error.args: error.message = error.args[0]
            response_data, response_status = error_handler.get_response_data_and_status(
                error)
        return Response(response_data, status=response_status)
Beispiel #11
0
 def delete(self, request, *args, **kwargs):
     try:
         user = request.user
         request_password = request.data.get('password')
         if not request_password:
             raise Exception(
                 {'message': "Request doesn't contain password field!"})
         validated_user = authenticate(username=user.username,
                                       password=request_password)
         if validated_user:
             user.delete()
             response_status = status.HTTP_200_OK
             response_data = generate_formatted_response(
                 status=True, payload={'message': 'Success removed!'})
         else:
             raise Exception({
                 'message': 'Password is incorrect!',
                 'status': status.HTTP_403_FORBIDDEN
             })
     except Exception as error:
         response_data, response_status = error_handler.get_response_data_and_status(
             error)
     return Response(response_data, status=response_status)
Beispiel #12
0
    def put(self, request, *args, **kwargs):
        try:
            user_pk = request.user.pk
            user_instance = self.get_object(user_pk)
            serializer_data = request.data.get('user', {})
            serializer = UserSerializer(user_instance,
                                        data=serializer_data,
                                        partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            response_status = status.HTTP_200_OK
            response_data = generate_formatted_response(
                status=True, payload={'user': serializer.data})
        except (ObjectDoesNotExist, ValueError) as error:
            error.message = "This user doesn't exists!"
            error.status = status.HTTP_404_NOT_FOUND
            response_data, response_status = error_handler.get_response_data_and_status(
                error)
        except Exception as error:
            response_data, response_status = error_handler.get_response_data_and_status(
                error)

        return Response(response_data, status=response_status)