def post(self, request): serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response({'error': serializer.errors}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def put(self, request, book_id): book = self.get_object(book_id) serializer = BookSerializer(instance=book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response({"error": serializer.errors})
def get(self, request, pk=None): response = dict() response['status_code'] = status.HTTP_200_OK response['status'] = 'success' if pk: book_instance = self.get_object(pk) if book_instance: response['data'] = BookSerializer(book_instance).data return Response(response) else: response['status_code'] = status.HTTP_404_NOT_FOUND response['status'] = 'failed' response['message'] = 'Book not found' return Response(response) books = Book.objects.all() serializer = BookSerializer(books, many=True) if not serializer: response['data'] = [] return Response(response) response['data'] = serializer.data return Response(response)
def put(self, request, book_id): book = self.get_object(book_id) serializer = BookSerializer(instance=book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response({'error': serializer.errors})
def post(self, request, id): book = Book(publishing_house=self.get_object(id)) serializer = BookSerializer(book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors)
def add_book(request): if request.method == "POST": stream = BytesIO(request.body) data = JSONParser().parse(stream) serializer = BookSerializer(data=data) if not serializer.is_valid(): return JsonResponse({"status": "fail", "msg": serializer.errors}) serializer.save() return JsonResponse({"status": "OK", "msg": u"הספר נוסף בהצלחה!"}) else: return HttpResponse(":3")
def book_list(request): if request.method == 'GET': books = Book.objects.all() serializer = BookSerializer(books, many=True) return Response(serializer.data) if request.method == 'POST': serializer = BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def books_list(request): if request.method == 'GET': books = Book.objects.all() books_json = [books.to_json() for book in books] return JsonResponse(books_json, safe=False) elif request.method == 'PUT': s = BookSerializer(instance=books, data=request.data) if s.is_valid(): s.save() return Response(s.data) return Response({'error': s.errors}) elif request.method == 'DELETE': books.delete() return JsonResponse({'deleted': True})
def post(self, request): book = json.loads(request.body.decode('utf-8')) response = dict() if book is None: return Response(status.HTTP_404_NOT_FOUND) serializer = BookSerializer(data=book) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() response['status_code'] = status.HTTP_201_CREATED response['status'] = 'success' response['data'] = {'book': BookSerializer(article_saved).data} return Response(response)
def get(self, request, id): try: return Response(BookSerializer(Book.objects.get(id=id)).data, status=status.HTTP_200_OK) except: return Response({"exception": "happened"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def get(self, request): try: return Response(BookSerializer(Book.objects.all(), many=True).data, status=status.HTTP_200_OK) except: return Response({"exception": "happenпатриаршие пруды ed"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def test_create_book(self): """ This test ensures that all books added in the setUp method exist when we make a GET request to the books/ endpoint """ # authors = [Author.objects.create(name="George R. R. Martin")] authors = [{"name": "George R. R. Martin"}] book = { "name": "A Game of Thrones", "isbn": "123-9999999990", "authors": authors, "number_of_pages": 694, "publisher": "Bantam Books", "country": "United States", "release_date": "1996-08-01" } # hit the API endpoint response = self.client.post(reverse("books"), book, format='json') # fetch the data from db expected = Book.objects.get(isbn="123-9999999990") serialized = BookSerializer(expected, many=False) self.assertEqual(response.data['data']['book'], serialized.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_book_serializer_output(minimal_book, author): serializer = BookSerializer(instance=minimal_book) assert serializer.data assert serializer.data.keys() == {"author", "name", "tags"} assert serializer.data["author"] == author.name assert serializer.data["name"] == minimal_book.name assert serializer.data["tags"] == ""
def setUp(self) -> None: self.publication_language_id = PublicationLanguage.objects.get_or_create( language="en")[0] self.author_id = Author.objects.get_or_create(name="test_author")[0] self.book = Book.objects.create( isbn="1234567891234", title="test_title", publication_year=2008, page_count=2008, cover="https://google.pl", publication_language=self.publication_language_id) self.book.author.set([self.author_id]) self.serializer_book = BookSerializer(instance=self.book) self.book_attributes = { "isbn": "1234567891234", "title": "test_title", "publication_year": 2008, "page_count": 2008, "cover": "https://google.pl", "publication_language": "en", "author": "test_author" }
def test_get_books(self): resp = self.authorizedClient.get(reverse('api:books-list'), format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) books = Book.objects.all() serializer = BookSerializer(books, many=True) self.assertEqual(resp.data['results'], serializer.data)
def test_filter_publication_date(self): book_first = Book.objects.create( isbn="1234567891234", title="test_title", publication_year=2008, page_count=2008, cover="https://google.pl", publication_language=self.publication_language_id) book_first.author.set([self.author_id]) book_second = Book.objects.create( isbn="1234567891235", title="test_title123", publication_year=2018, page_count=2008, cover="https://google.pl", publication_language=self.publication_language_id) book_second.author.set([self.author_id]) url = f"{reverse('api:book_list')}?publication_year__gte=&publication_year__lte=2013" response = client.get(url) books = Book.objects.filter(publication_year__lte=2013) serializer = BookSerializer(books, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_empty_list_books(self): response = client.get(reverse("api:book_list")) books = Book.objects.all() serializer = BookSerializer(books, many=True) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def books_by_genre(request, id): try: genre = Genre.objects.get(id=id) return Response(BookSerializer(genre.book_set.all(), many=True).data, status=status.HTTP_200_OK) except: return Response({"exception": "happened"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def book_detail(request, pk): book = get_object_or_404(Book, pk=pk) if request.method == 'GET': serializer = BookSerializer(book) return Response(serializer.data) elif request.method == 'PUT': serializer = BookSerializer(book, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': book.delete() return HttpResponse(status=status.HTTP_204_NO_CONTENT)
def get(self, request, category_id): category_books = [] books = Book.objects.all() for book in books: if book.category.id == category_id: category_books.append(book) serializer = BookSerializer(category_books, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def list(self, request): books = self.get_queryset() serializer = BookSerializer(books, many=True) response = { 'status_code': 200, 'status': 'success', 'data': serializer.data } return Response(response)
def retrieve(self, request, pk=None): book = Booking.objects.get(pk=pk) serializer = BookSerializer(book) response = { 'resultCode': 100, 'resultText': 'SUCCESS', 'content': serializer.data } return JsonResponse(response)
def list(self, request): books = Booking.objects.all() serializer = BookSerializer(books, many=True) response = { 'resultCode': 100, 'resultText': 'SUCCESS', 'content': serializer.data } return JsonResponse(response)
def test_update_book(self): # Attempt to update book information resp = self.authorizedClient.patch(reverse('api:books-detail', kwargs={'pk': self.book1.id}), {'title': 'Edited Title', "author_ids": [self.author1.id]}, format='json') self.assertEqual(resp.status_code, status.HTTP_200_OK) self.book1 = Book.objects.get(pk=self.book1.id) serializer = BookSerializer(self.book1) self.assertEqual(resp.data, serializer.data)
def retrieve(self, request, pk=None): queryset = Book.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = BookSerializer(user, many=False) response = { 'status_code': 201, 'status': 'success', 'data': serializer.data } return Response(response)
def test_book_serializer_output_with_tags(minimal_book, author, tag_1, tag_2): minimal_book.tags.add(tag_1) minimal_book.tags.add(tag_2) minimal_book.save() serializer = BookSerializer(instance=minimal_book) assert serializer.data assert serializer.data.keys() == {"author", "name", "tags"} assert serializer.data["author"] == author.name assert serializer.data["name"] == minimal_book.name assert serializer.data["tags"] == f"{tag_1.name},{tag_2.name}"
def setUp(self): self.book_attributes = { 'author': 'J.R.R. Tolkien', 'title': 'The Hobbit' } self.book = Book.objects.create(**self.book_attributes) self.review = [ Review.objects.create(book=self.book, review=n % 5) for n in range(0, 5) ] self.serializer = BookSerializer(instance=self.book)
def test_create_book(self): resp = self.authorizedClient.post(reverse('api:books-list'), {"title": "A new Book", "isbn": "isbn123", "date_of_publication": "2021-03-10", "author_ids": [2]}, format='json') self.assertEqual(resp.status_code, status.HTTP_201_CREATED) created_book = Book.objects.get(pk=resp.data['id']) serializer = BookSerializer(created_book) self.assertEqual(resp.data, serializer.data)
def patch(self, request, pk=None): response = {} book = json.loads(request.body.decode('utf-8')) book_instance = self.get_object(pk) if book_instance is None: response['status_code'] = status.HTTP_404_NOT_FOUND response['status'] = 'failed' response['message'] = 'Book not found' return Response(response) serializer = BookSerializer(book_instance, data=book, partial=True) if serializer.is_valid(raise_exception=True): article_saved = serializer.save() response['status_code'] = status.HTTP_201_CREATED response['status'] = 'success' response[ 'message'] = 'The book My First Book was updated successfully' response['data'] = {'book': BookSerializer(article_saved).data} return Response(response)
def book_list_book(request, pk): """ Retrieve, update or delete a code snippet. """ try: book = Book.objects.get(pk=pk) except Book.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = BookSerializer(book) return Response(serializer.data)
def perform_create(self, serializer): serializer.save(self.request) # convert to BookSerializer book = Booking.objects.get(pk=serializer.data['id']) serializer = BookSerializer(book) result = {} result["resultCode"] = 100 result["resultText"] = "SUCCESS" result["content"] = serializer.data return JsonResponse(result)
def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) validated_data = serializer.validated_data book = Book.objects.create(**validated_data) response = { 'status_code': 200, 'status': 'success', 'data': [ {'book': BookSerializer(book).data} ] } return Response(response)