def get_all_books():
    books = []
    if request.method == 'GET':
        print('THis is get request')
        for book in Book.query.all():
            temp_dict = {
                'book_name': book.book_name,
                'book_price': book.book_price,
                'book_num': book.book_num
            }
            books.insert(0, temp_dict)
        return jsonify(books)
    elif request.method == 'POST':
        print('This is post request', request.get_json())
        request_data = request.get_json()
        if valid_book(request_data):
            new_book = Book(book_name=request_data['book_name'],
                            book_price=request_data['book_price'],
                            book_num=request_data['book_num'])
            new_book.save()
            books.append(request.get_json())
            response = Response(
                "", 201,
                mimetype="application/json")  # 201 response i.e created
            response.headers['Location'] = '/books/' + str(
                request_data['book_num'])  # link in the header
            redirect(url_for('get_all_books'))
            return response
        return Response("", 400, mimetype="application/json")
Esempio n. 2
0
def add_book(request, author_id):
    a = Author.objects.get(pk=author_id)
    data = request.POST
    b = Book()
    b.title = data.get("title", "")
    b.author = a
    b.save()

    return HttpResponseRedirect(reverse('books:book_list'))
Esempio n. 3
0
 def test_buy_book(self):
     book = Book(
         name='foo',
         description='bar',
         price=Decimal('0.00001'),
         link='http://example.com/book.pdf',
     )
     book.save()
     self.user.profile.bought_books.add(book)
     self.assertEqual(list(book.buyers.all()), [self.user.profile])
Esempio n. 4
0
def add_book():
    with open("bookdb/books.csv") as f:
        reader = csv.reader(f)
        header = next(
            reader)  # skip the first line which is a field description
        for item in reader:
            dt = Book(isbn=item[11],
                      title=item[1],
                      author=item[2],
                      publish_date=item[13],
                      average_rating=item[3],
                      ratings_count=item[4],
                      page_count=item[9],
                      description=item[7])
            dt.save()
            print(f"Added {dt.isbn}")
Esempio n. 5
0
class BookModelTest(TestCase):
    def setUp(self):
        self.book = Book(
            name='Clean code',
            description='How to write <i>code</i> well',
            price=Decimal('0.01'),
            link='http://amazons3.com/rmartin/clean_code.pdf',
        )
        self.book.save()

    def test_string_representation(self):
        self.assertEqual(str(self.book), 'Clean code')

    def test_add_few_books_authors(self):
        uncle_bob = Author(name='Robert', surname='Marting')
        uncle_bob.save()
        self.book.authors.add(uncle_bob)
        levi_metthew = self.book.authors.create(name='Levi Matthew')
        self.assertEqual(list(levi_metthew.books.all()), [self.book])
    def setUp(self):
        uncle_bob = Author(name='Robert', surname='Martin')
        uncle_bob.save()
        mcconnell = Author(name='Steve', surname='McConnell')
        mcconnell.save()
        myers = Author(name='Glenford', surname='Myers')
        myers.save()
        levi_metthew = Author(name='Levi Metthew')
        levi_metthew.save()

        clean_code = Book(
            name='Clean code',
            description='How to write <i>code</i> well',
            price=Decimal('0.01'),
            link='http://amazons3.com/books/clean_code.pdf',
        )
        clean_code.save()
        clean_code.authors.add(uncle_bob)

        code_complete = Book(
            name='Code complete',
            description='How to write <i>code</i> well',
            price=Decimal('0.02'),
            link='http://amazons3.com/books/code_complete.pdf',
        )
        code_complete.save()
        code_complete.authors.add(mcconnell)
        code_complete.authors.add(levi_metthew)

        the_art_of_software_testing = Book(
            name='The art of software testing',
            description='The first book about software testing',
            price=Decimal('0.003'),
            link='http://amazons3.com/books/the_art_of_software_testing.pdf')
        the_art_of_software_testing.save()
        the_art_of_software_testing.authors.add(myers)
        the_art_of_software_testing.authors.add(levi_metthew)

        alobachev = User(username='******', email='*****@*****.**')
        alobachev.set_password('password')
        alobachev.save()
        alobachev.profile.bought_books.add(code_complete)
        achistyakov = User(username='******',
                           email='*****@*****.**')
        achistyakov.set_password('password')
        achistyakov.save()
        achistyakov.profile.bought_books.add(code_complete,
                                             the_art_of_software_testing)
        aukupnik = User(username='******', email='*****@*****.**')
        aukupnik.set_password('password')
        aukupnik.save()
        aukupnik.profile.bought_books.add(code_complete,
                                          the_art_of_software_testing,
                                          clean_code)
        aapostle = User(username='******', email='*****@*****.**')
        aapostle.set_password('password')
        aapostle.save()

        achistyakov.profile.cards.create(name='VISA***1111',
                                         payment_number='1111-1111-1111-1111')
from bookstore.models import Author, Book

some_author = Author(name='Chris Conlan')
some_author.save()

some_book = Book(author=some_author,
                 title='Fast Python',
                 subtitle='Re-learn the basics')
some_book.save()
Esempio n. 8
0
    def test_add_book_and_review(self):
        num_cat = Category.objects.filter(owner='kati')
        self.assertEqual(num_cat.count(), 0)

        first_cat = Category(name='Novel', owner='kati')
        first_cat.save()

        num_cat = Category.objects.filter(owner='kati')
        self.assertEqual(num_cat.count(), 1)

        first_book = Book(title='The Thief of Baramos',
                          author='Rabbit',
                          owner='kati',
                          category=num_cat[0])
        first_book.save()
        book = Book.objects.filter(owner='kati')
        self.assertEqual(book.count(), 1)

        second_book = Book(title='The Thief of Baramos vol2',
                           author='Rabbit',
                           owner='kati',
                           category=num_cat[0])
        second_book.save()
        book = Book.objects.filter(owner='kati')
        self.assertEqual(book.count(), 2)

        first_review = Review(book=book[0],
                              timestamp=timezone.now(),
                              review_message='สนุกมาก',
                              rating=4)
        first_review.save()

        avg = Book.objects.filter(id=book[0].id).update(
            avg_rating=Review.objects.filter(book=book[0]).aggregate(
                Avg('rating')).get('rating__avg', 0.00))
        update = Book.objects.filter(id=book[0].id).update(
            update_review=timezone.now())

        second_review = Review(book=book[1],
                               timestamp=timezone.now(),
                               review_message='สนุกมาก',
                               rating=4)
        second_review.save()

        third_review = Review(book=book[1],
                              timestamp=timezone.now(),
                              review_message='สนุกมาก',
                              rating=5)
        third_review.save()

        avg = Book.objects.filter(id=book[1].id).update(
            avg_rating=Review.objects.filter(book=book[1]).aggregate(
                Avg('rating')).get('rating__avg', 0.00))
        update = Book.objects.filter(id=book[1].id).update(
            update_review=timezone.now())

        num_review = Review.objects.all()
        self.assertEqual(num_review.count(), 3)
        self.assertEqual(book[0].avg_rating, 4)
        self.assertEqual(book[1].avg_rating, 4.5)

        response = self.client.post('/kati/2/')
        self.assertEqual(response.templates[0].name,
                         'bookstore/display_title.html')
Esempio n. 9
0
class BookstoreViewsTest(TestCase):
    """Test suite for Bookstore views"""
    def setUp(self):
        self.user = User(username='******',
                         password='******',
                         email='*****@*****.**')
        self.user.save()

        self.author = Author(first_name='Ernest', last_name='Hemingway')
        self.author.save()

        self.book = Book(title='A Farewell to Arms',
                         author=self.author,
                         publication_year=1929)
        self.book.save()

        self.book2 = Book(title='The Sun Also Rises',
                          author=self.author,
                          publication_year=1926)
        self.book2.save()

        self.book3 = Book(title='For Whom The Bell Tolls',
                          author=self.author,
                          publication_year=1940)
        self.book3.save()

        self.review = Review(user=self.user,
                             book=self.book,
                             timestamp=datetime.datetime.now(),
                             review_message='Good Book',
                             rating=5)

    def testIndex(self):
        """Test bookstore index view"""
        response = self.client.get(reverse('bookstore:index'))
        #Just make sure the page loads, that's all
        self.assertEqual(response.status_code, 200)

    def testBookReviewList(self):
        """Test books review list view"""
        #if no book id was specified, it should return an error
        self.assertRaises(
            NoReverseMatch,
            lambda: self.client.get(reverse('bookstore:book_review_list')))

        #if the book id is invalid, it should return an error
        response = self.client.get(
            reverse('bookstore:book_review_list', kwargs={'book_id': 0}))
        self.assertEqual(response.status_code, 404)

        #if the book id is valid, it should give the right book
        response = self.client.get(
            reverse('bookstore:book_review_list', kwargs={'book_id': 1}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['book'].title, 'A Farewell to Arms')

    def testUserReviewList(self):
        """Test user review list view"""
        #if no user id was specified, it should return an error
        self.assertRaises(
            NoReverseMatch,
            lambda: self.client.get(reverse('bookstore:user_review_list')))

        #if the user id is invalid, it should return an error
        response = self.client.get(
            reverse('bookstore:user_review_list', kwargs={'user_id': 0}))
        self.assertEqual(response.status_code, 404)

        #if the username is invalid, it should return an error
        response = self.client.get(
            reverse('bookstore:user_review_list',
                    kwargs={'username': '******'}))
        self.assertEqual(response.status_code, 404)

        #if the user id is valid, it should give the right book
        response = self.client.get(
            reverse('bookstore:user_review_list', kwargs={'user_id': 1}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['queried_user'].username, 'user')
        self.assertEqual(response.context['queried_user'].pk, 1)

        #if the username is valid, it should give the right book
        response = self.client.get(
            reverse('bookstore:user_review_list', kwargs={'username': '******'}))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['queried_user'].username, 'user')
        self.assertEqual(response.context['queried_user'].pk, 1)

    def testBookList(self):
        """Test book list view"""
        #make sure the context has a list of books, in alphabetical order
        response = self.client.get((reverse('bookstore:book_list')))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['book_list'][0].title,
                         'A Farewell to Arms')
        self.assertEqual(response.context['book_list'][1].title,
                         'For Whom The Bell Tolls')
        self.assertEqual(response.context['book_list'][2].title,
                         'The Sun Also Rises')
Esempio n. 10
0
class BookstoreViewsTest(TestCase):
    """Test suite for Bookstore views"""

    def setUp(self):
        self.user = User(username='******', password='******', email='*****@*****.**')
        self.user.save()

        self.author = Author(first_name='Ernest', last_name='Hemingway')
        self.author.save()

        self.book = Book(title='A Farewell to Arms', author=self.author,
            publication_year=1929)
        self.book.save()

        self.book2 = Book(title='The Sun Also Rises', author=self.author,
            publication_year=1926)
        self.book2.save()

        self.book3 = Book(title='For Whom The Bell Tolls', author=self.author,
            publication_year=1940)
        self.book3.save()

        self.review = Review(
            user=self.user,
            book=self.book,
            timestamp=datetime.datetime.now(),
            review_message='Good Book',
            rating=5
        )

    def testIndex(self):
        """Test bookstore index view"""
        response = self.client.get(reverse('bookstore:index'))
        #Just make sure the page loads, that's all
        self.assertEqual(response.status_code, 200)

    def testBookReviewList(self):
        """Test books review list view"""
        #if no book id was specified, it should return an error
        self.assertRaises(
            NoReverseMatch,
            lambda: self.client.get(reverse('bookstore:book_review_list'))
        )

        #if the book id is invalid, it should return an error
        response = self.client.get(reverse(
            'bookstore:book_review_list',
            kwargs = {'book_id':0}
        ))
        self.assertEqual(response.status_code, 404)

        #if the book id is valid, it should give the right book
        response = self.client.get(reverse(
            'bookstore:book_review_list',
            kwargs = {'book_id':1}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['book'].title, 'A Farewell to Arms')

    def testUserReviewList(self):
        """Test user review list view"""
        #if no user id was specified, it should return an error
        self.assertRaises(
            NoReverseMatch,
            lambda: self.client.get(reverse('bookstore:user_review_list'))
        )

        #if the user id is invalid, it should return an error
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'user_id':0}
        ))
        self.assertEqual(response.status_code, 404)

        #if the username is invalid, it should return an error
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'username':'******'}
        ))
        self.assertEqual(response.status_code, 404)

        #if the user id is valid, it should give the right book
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'user_id':1}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['queried_user'].username, 'user')
        self.assertEqual(response.context['queried_user'].pk, 1)

        #if the username is valid, it should give the right book
        response = self.client.get(reverse(
            'bookstore:user_review_list',
            kwargs = {'username':'******'}
        ))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['queried_user'].username, 'user')
        self.assertEqual(response.context['queried_user'].pk, 1)

    def testBookList(self):
        """Test book list view"""
        #make sure the context has a list of books, in alphabetical order
        response = self.client.get((reverse('bookstore:book_list')))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['book_list'][0].title,
            'A Farewell to Arms')
        self.assertEqual(response.context['book_list'][1].title,
            'For Whom The Bell Tolls')
        self.assertEqual(response.context['book_list'][2].title,
            'The Sun Also Rises')
Esempio n. 11
0
    book.publisher_id = publisher
    book.published_date = published_date

    author_id = [random.randint(1, 1572)]

    if cnt % 17 == 0:
        for i in range(1, 3):
            author_id.append(random.randint(1, 1572))

    if cnt % 29 == 0:
        for i in range(1, 4):
            author_id.append(random.randint(1, 1572))

    if cnt % 71 == 0:
        for i in range(1, 5):
            author_id.append(random.randint(1, 1572))

    if cnt % 97 == 0:
        for i in range(1, 7):
            author_id.append(random.randint(1, 1572))

    book.save()

    tAuthors = Author.objects.filter(pk__in=author_id)
    # print(author_id, tAuthors)

    book.authors.set(tAuthors)

    print(books)

    cnt += 1