Exemplo n.º 1
0
def books_list(request):
    if request.method == 'GET':
        #check whether the request object contains the title parameter
        title = request.query_params.get('title', None)
        #Get all the Book Details existing in database
        book_data = getBookData()
        inventoryDict = dict()
        bookData = list()
        #When the title is not empty/None
        if title is not None:
            #create a new dict of inventory
            for item in book_data:
                inventoryDict[item['bookid']] = item['quantity']
            #Get the details based on the input title
            response = books_search(title)
            for data in response['items']:
                #initialize the quantity as zero for all books
                quantity = 0
                #check whether the bookid exists in database
                bookExists = getBookId(data)
                #IF the bookid exists in database update the quantity accordingly
                if bookExists in inventoryDict.keys():
                    quantity = inventoryDict[bookExists]
                #New list of dict is generated
                bookData.append({
                    "title": getTitle(data),
                    "link": getLink(data),
                    "thumbnail": getThumbnail(data),
                    "quantity": quantity
                })
                #The old list of dict is overwritten with new data
                book_data = bookData
        else:
            #when the title is empty consider the data in inventory
            for data in range(len(book_data)):
                response = get_book_data_by_id(book_data[data].get('bookid'))
                #when response is not empty
                if response != '':
                    book_data[data].update({'title': getTitle(response)})
                    book_data[data].update({'link': getLink(response)})
                    book_data[data].update(
                        {'thumbnail': getThumbnail(response)})
        return JsonResponse(book_data, safe=False)

    elif request.method == 'POST':
        #parse the request object and store it as JSON
        book_data = JSONParser().parse(request)
        #Convert the JSON to Object
        book_serializer = BooksSerializer(data=book_data)
        #check whether the created object is valid
        if book_serializer.is_valid():
            book_serializer.save()
            #return 201 when the objects gets created in database
            return JsonResponse(book_serializer.data,
                                status=status.HTTP_201_CREATED)
        #if there is a failure return as bad request
        return JsonResponse(book_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 2
0
def books_list(request, format=None):
	"""
	List all books, or create a new book.
	"""
	if request.method == 'GET':
		books = Books.objects.all()
		serializer = BooksSerializer(books, many=True)
		return Response(serializer.data)

	elif request.method == 'POST':
		serializer = BooksSerializer(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)
Exemplo n.º 3
0
def book_detail(request, pk):
    try:
        bookInventory = BookInventory.objects.get(pk=pk)
    except BookInventory.DoesNotExist:
        return JsonResponse({'message': 'The BookInventory does not exist'},
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        books_serializer = BooksSerializer(bookInventory)
        return JsonResponse(books_serializer.data)
    #update the existing data in database
    elif request.method == 'PUT':
        book_data = JSONParser().parse(request)
        books_serializer = BooksSerializer(bookInventory, data=book_data)
        if books_serializer.is_valid():
            books_serializer.save()
            return JsonResponse(books_serializer.data)
        return JsonResponse(books_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
    #delete the book in database
    elif request.method == 'DELETE':
        bookInventory.delete()
        return JsonResponse(
            {'message': 'BookInventory was deleted successfully!'},
            status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 4
0
 def books_owned_author(self, request, pk=None):
     user = self.get_object()
     author = request.data.get('author')
     books = Book.objects.all().filter(Q(author=author),
                                       Q(bought_by=user)).distinct()
     if len(books) == 0:
         return Response(status=status.HTTP_204_NO_CONTENT)
     serialized = BooksSerializer(books, many=True)
     return Response(serialized.data)
Exemplo n.º 5
0
 def get(self, request, *args, **kwargs):
     """ Handles :model:`books.Books` for listing a single object. """
     try:
         book = Books.objects.get(id=kwargs['id'])
     except Books.DoesNotExist:
         return Response({}, status=status.HTTP_202_ACCEPTED)
     else:
         serialized_book = BooksSerializer(book)
         return Response(serialized_book.data, status=status.HTTP_200_OK)
Exemplo n.º 6
0
def books_detail(request, pk, format=None):
	"""
	Retrieve, update or delete a book instance.
	"""
	try:
		book = Books.objects.get(pk=pk)
	except Books.DoesNotExist:
		return Response(status=status.HTTP_404_NOT_FOUND)

	if request.method == 'GET':
		serializer = BooksSerializer(book)
		return Response(serializer.data)

	elif request.method == 'PUT':
		serializer = BooksSerializer(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 Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 7
0
 def book_time(self, request, pk=None):
     start = request.data.get('start')
     end = request.data.get('end')
     if start and end:
         books = Book.objects.all().filter(Q(pub_date__gt=start),
                                           Q(pub_date__lt=end))
     elif start and not end:
         books = Book.objects.all().filter(Q(pub_date__gt=start))
     elif not start and end:
         books = Book.objects.all().filter(Q(pub_date__lt=end))
     else:
         return Response(status=status.HTTP_204_NO_CONTENT)
     serialized = BooksSerializer(books, many=True)
     return Response(serialized.data)
Exemplo n.º 8
0
 def post(self, request, *args, **kwargs):
     criterion = CriteriaSerializer(data=request.data)
     if criterion.is_valid():
         records = requests.get(self.url, params=criterion.data).json()
         deserialized_records = RawDataSerializer(data=records['items'],
                                                  many=True)
         if deserialized_records.is_valid():
             new_books = deserialized_records.save()
             serialized_new_books = BooksSerializer(new_books, many=True)
             return Response({'saved_books': serialized_new_books.data},
                             status=status.HTTP_201_CREATED)
         else:
             return Response({'error': 'Sorry, an internal server error'},
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)
     else:
         return Response({'error': 'Wrong body-data format'},
                         status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
Arquivo: views.py Projeto: DelilaM/lab
def books_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        books = Books.objects.all()
        serializer = BooksSerializer(books, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = BooksSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

    @csrf_exempt
    def books_detail(request, pk):
        """
        Retrieve, update or delete a code snippet.
        """
        try:
            books = Books.objects.get(pk=pk)
        except Books.DoesNotExist:
            return HttpResponse(status=404)

        if request.method == 'GET':
            serializer = BooksSerializer(books)
            return JsonResponse(serializer.data)

        elif request.method == 'PUT':
            data = JSONParser().parse(request)
            serializer = BooksSerializer(books, data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data)
            return JsonResponse(serializer.errors, status=400)

        elif request.method == 'DELETE':
            books.delete()
            return HttpResponse(status=204)
Exemplo n.º 10
0
Arquivo: views.py Projeto: DelilaM/lab
    def books_detail(request, pk):
        """
        Retrieve, update or delete a code snippet.
        """
        try:
            books = Books.objects.get(pk=pk)
        except Books.DoesNotExist:
            return HttpResponse(status=404)

        if request.method == 'GET':
            serializer = BooksSerializer(books)
            return JsonResponse(serializer.data)

        elif request.method == 'PUT':
            data = JSONParser().parse(request)
            serializer = BooksSerializer(books, data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data)
            return JsonResponse(serializer.errors, status=400)

        elif request.method == 'DELETE':
            books.delete()
            return HttpResponse(status=204)
Exemplo n.º 11
0
 def books(self, request, pk=None):
     books = Book.objects.all().filter(author=pk)
     serialized = BooksSerializer(books, many=True)
     return Response(serialized.data)
Exemplo n.º 12
0
 def books_owned(self, request, pk=None):
     user = self.get_object()
     books = Book.objects.all().filter(Q(bought_by=user)).distinct()
     serialized = BooksSerializer(books, many=True)
     return Response(serialized.data)
Exemplo n.º 13
0
def getBookData():
    books = BookInventory.objects.all()
    books_serializer = BooksSerializer(books, many=True)
    #convert orderd dict to dict
    book_data = loads(dumps(books_serializer.data))
    return book_data
Exemplo n.º 14
0
 def get_books(self, request, pk=None):
     books = Book.objects.all().filter(info_mentions=pk)
     if not books:
         return Response(status=status.HTTP_204_NO_CONTENT)
     serialized = BooksSerializer(books, many=True)
     return Response(serialized.data)