def validate(self, attrs): """ To validate the wish list items :param attrs: :return: """ #: Convert the string passed. wishlist_items = attrs.get('wishlist') for book_id in wishlist_items: #: Validate the book ids passed to ensure they are real ones. book_instance = book_validators.validate_book_exists_based_on_id( book_id) if self.context['request'].data['action'] == 'add': #: We need to check whether book is unavailable before adding it to wish list if not book_validators.validate_books_status(book_instance): raise err.ValidationError( 'Book is already available . You can lent it now.', 400) #: We need to check book is already in wish list if it exist no need to add once again if book_validators.check_book_exist_in_wishlist( book_instance, self.instance): raise err.ValidationError( 'Book already exist in your wish list', 400) else: #: We need to check book is already in wish list inorder to remove it if not book_validators.check_book_exist_in_wishlist( book_instance, self.instance): raise err.ValidationError( 'Book not exist in your wish list', 400) return attrs
def update(self, request, *args, **kwargs): """ This will update the status of a book from available to borrowed or viceverca :param request: {"book_id": <book_id>, status="available/borrowed"} :param args: :param kwargs: :return: {"message": "Success msg"} """ # get the book instance to be updated book_id = request.data.get("book_id", None) # Check if book exists book_instance = book_validators.validate_book_exists_based_on_id( book_id) serializer = self.get_serializer(book_instance, data=request.data, partial=True) try: if serializer.is_valid(raise_exception=True): self.perform_update(serializer) except Exception as e: logger.error( "Error inside post function inside BookStatusUpdateView class. ERROR {}" .format(str(e))) raise err.ValidationError(*(e, 400)) response = Response({"message": book_constants.STATUS_UPDATED}, status=status.HTTP_200_OK) return response
def update(self, request, *args, **kwargs): """ :param request: {"uid": <user_uid>, "action": "add/delete", "wishlist": [<book_uid1>, <book_uid2>, etc..] :param args: :param kwargs: :return: {"message": "Success msg"} """ # get the user instance to be updated user_uid = request.data.get("uid", None) # Check if user exists user_instance = book_validators.validate_user_exists_based_on_uid( user_uid) serializer = self.get_serializer(user_instance, data=request.data, partial=True) try: if serializer.is_valid(raise_exception=True): self.perform_update(serializer) except Exception as e: logger.error( "Error inside post function inside WishListUpdateView class. ERROR {}" .format(str(e))) raise err.ValidationError(*(e, 400)) response = Response({"message": book_constants.WISHLIST_UPDATED}, status=status.HTTP_200_OK) return response
def create_book(self, data): try: authors = data.pop('authors').split(',') book_instance = Book.objects.create(**data) for author_name in authors: author_instance = self.create_or_get_authors(author_name) book_instance.authors.add(author_instance) except Exception as e: logger.error('Error inside create book method') raise err.ValidationError(*(400, e.args[0]))
def create_or_get_authors(self, author_name): """ Create authors for books :return: author instance """ try: # Check if an author with give name exist # If so get the first author with given name else create one author, created = Author.objects.get_or_create( username=author_name) return author except Exception as e: logger.error('Error inside get or create function for author') raise err.ValidationError(*(400, e))
def update(self, request, *args, **kwargs): """ :param request: :param args: :param kwargs: :return: """ books = Book.objects.all() for book_instance in books: #: get the current amazon id of book current_amazon_id = book_instance.amazon_id #: Get the isbn of book isbn = book_instance.isbn #: Initialise it to existing for checking amazon_id = current_amazon_id try: api_response = requests.get(settings.OPEN_LIBRARY_URL + isbn) if api_response.status_code == 200: amazon_id = json.loads(api_response.text).get( 'ISBN:' + isbn).get('identifiers').get('amazon')[0] except: #: There may be instances where there is no response pass #: Perform the update only if there is a difference in existing and the new if current_amazon_id != amazon_id: request.data['amazon_id'] = amazon_id serializer = self.get_serializer(book_instance, data=request.data, partial=True) try: if serializer.is_valid(raise_exception=True): self.perform_update(serializer) except Exception as e: logger.error( "Error inside post function inside BookAmazonUpdateView class. ERROR {}" .format(str(e))) raise err.ValidationError(*(e, 400)) response = Response({"message": book_constants.AMAZON_UPDATED}, status=status.HTTP_200_OK) return response
def handle(self, *args, **options): try: #: Before trying to import delete the existing to avoid duplication Book.objects.all().delete() with open('Backend Data.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 1 for row in csv_reader: if line_count == 1: line_count += 1 continue print(row[2]) data = dict(id=row[0], isbn=row[1], authors=row[2], published_year=int(row[3]), title=row[4], language=row[5]) self.create_book(data) line_count += 1 except Exception as e: logger.error('Error inside handle for sync db') raise err.ValidationError(*(400, e.args[0]))