Esempio n. 1
0
    def handle_noargs(self, **options):
        books = []
        book = Book()
        book.uuid = "aaa"
        book.title = "Learning Web Design: A Beginner's Guide to HTML, CSS, JavaScript, and Web Graphics"
        book.author_lastname = "Robbins"
        book.author_firstname = "Jennifer"
        book.description = """
        Do you want to build web pages, but have no previous experience? This friendly guide is the perfect place to start. You'll begin at square one, learning how the Web and web pages work, and then steadily build from there. By the end of the book, you'll have the skills to create a simple site with multi-column pages that adapt for mobile devices.
        
        Learn how to use the latest techniques, best practices, and current web standards--including HTML5 and CSS3. Each chapter provides exercises to help you to learn various techniques, and short quizzes to make sure you understand key concepts.
        
        This thoroughly revised edition is ideal for students and professionals of all backgrounds and skill levels, whether you're a beginner or brushing up on existing skills.
        """
        book.isbn10 = "1449319270"
        book.publisher = "O'reilly"
        books.append(book)

        book = Book()
        book.uuid = "aab"
        book.title = "HTML and CSS: Design and Build Websites"
        book.author_lastname = "Duckett"
        book.author_firstname = "Jon"
        book.description = """
        Every day, more and more people want to learn some HTML and CSS. Joining the professional web designers and programmers are new audiences who need to know a little bit of code at work (update a content management system or e-commerce store) and those who want to make their personal blogs more attractive. Many books teaching HTML and CSS are dry and only written for those who want to become programmers, which is why this book takes an entirely new approach.

        Introduces HTML and CSS in a way that makes them accessible to everyone--hobbyists, students, and professionals--and it's full-color throughout
        Utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging
        Boasts a unique structure that allows you to progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure
        """
        book.isbn10 = "1118008189"
        book.publisher = "Wiley"
        books.append(book)

        book = Book()
        book.uuid = "aac"
        book.title = "JavaScript & jQuery: The Missing Manual"
        book.author_lastname = "McFarland"
        book.author_firstname = "David"
        book.description = """
        JavaScript lets you supercharge your HTML with animation, interactivity, and visual effects--but many web designers find the language hard to learn. This jargon-free guide covers JavaScript basics and shows you how to save time and effort with the jQuery library of prewritten JavaScript code. You'll soon be building web pages that feel and act like desktop programs, without having to do much programming.
        """
        book.isbn10 = "1449399029"
        book.publisher = "O'reilly"
        books.append(book)

        # add all the books that don't exist yet
        for book in books:
            try:
                Book.objects.get(uuid=book.uuid)
            except Book.DoesNotExist:
                book.save()
Esempio n. 2
0
 def setUpTestData(cls):
     Book.objects.bulk_create([
         Book(title='Test Book',
              author='John Doe',
              pub_date=1999,
              isbn=1234567890123,
              pages=30,
              lang='en'),
         Book(title='Książka',
              author='Adam Kowal',
              pub_date=1968,
              isbn=3210987654321,
              pages=45,
              lang='pl')
     ])
Esempio n. 3
0
def aabook(request):
    if request.method == 'POST':
        title = request.POST['title']
        author = request.POST['author']
        year = request.POST['year']
        publisher = request.POST['publisher']
        desc = request.POST['desc']
        cover = request.FILES['cover']
        pdf = request.FILES['pdf']
        current_user = request.user
        user_id = current_user.id
        username = current_user.username

        a = Book(title=title,
                 author=author,
                 year=year,
                 publisher=publisher,
                 desc=desc,
                 cover=cover,
                 pdf=pdf,
                 uploaded_by=username,
                 user_id=user_id)
        a.save()
        messages.success(request, 'Book was uploaded successfully')
        return redirect('albook')
    else:
        messages.error(request, 'Book was not uploaded successfully')
        return redirect('aabook_form')
Esempio n. 4
0
    def create(self, validated_data):
        # Check if category exists
        category = Category.objects.filter(
            name=validated_data['category']['name'])
        if category.count() <= 0:
            error = {'message': 'There is no such category'}
            raise serializers.ValidationError(error)

        # Check if author exists
        for author in validated_data['authors']:
            authors = Author.objects.filter(name=author['name'])
            if authors.count() <= 0:
                error = {'message': 'There is no such author'}
                raise serializers.ValidationError(error)

        title = validated_data['title']
        isbn = validated_data['isbn']
        pub_date = validated_data['pub_date']

        book = Book(title=title, isbn=isbn,
                    pub_date=pub_date, category=category[0])
        book.save()
        # After creating model instance add authors
        for author in validated_data['authors']:
            author_obj = Author.objects.filter(name=author['name'])[0]
            book.authors.add(author_obj)

        return book
Esempio n. 5
0
def accept_suggested_book(request, pk):
    """View function for accepting a SuggestedBook and creating a Book."""
    suggested_book = get_object_or_404(SuggestedBook, pk=pk)

    # if the request is a GET (the user requests the /suggestions/<book>/accept url)
    # create a Book from the SuggestedBook object and remove SuggestedBook
    if request.method == 'GET':
        # check to see if author already exists
        author = Author.objects.filter(name=suggested_book.author).first()
        if not author:
            author = Author(name = suggested_book.author)
            author.save()

        Book(
            title = suggested_book.title,
            author = author,
            url = suggested_book.url,
            description = suggested_book.description
        ).save()

        suggested_book.delete()

        messages.success(request, 'You accepted the suggested book.')

    # redirect to a new URL:
    return HttpResponseRedirect(request.GET.get("next"))
Esempio n. 6
0
def bookCreate(request):
    if request.method == "POST":
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)

        fields = ['code', 'title', 'author', 'date_launch', 'amount_available']

        for field in fields:
            try:
                body[field]
            except:
                return JsonResponse(
                    {"erro": 'campo ' + field + ' nao fornecido'}, safe=False)

        if verifyCode(body['code']):
            return JsonResponse(
                {"error": "código do livro já está cadastrado"})

        book = Book(code=body['code'],
                    title=body['title'],
                    author=body['author'],
                    date_launch=body['date_launch'],
                    date_register=body['date_register']
                    if 'date_register' in body else timezone.now(),
                    amount_available=body['amount_available'])

        book.save()

    return JsonResponse({})
Esempio n. 7
0
def add_book(request):
    if request.method == 'GET':
        return render_to_response('add_book.html')
    else:
        isempty = False
        if request.POST:
            post = request.POST
            post_attr_list = ['title', 'category', 'press', 'year', 'author', 'price', 'total', 'stock']
            old_book = Book.objects.filter(title=post['title']).first()
            for post_attr in post_attr_list:
                if post[post_attr] == '':
                    isempty = True
                    continue
            if isempty is False and old_book is None:
                new_book = Book(
                    title=post['title'],
                    category=post['category'],
                    press=post['press'],
                    year=post['year'],
                    author=post['author'],
                    price=post['price'],
                    total=post['total'],
                    stock=post['stock'],
                )
                new_book.save()
                add_msg = '添加成功!'
                return render(request, 'add_book.html', {'success_msg': add_msg})
            elif old_book is not None:
                add_msg = '该书已存在!'
                return render(request, 'add_book.html', {'fail_msg': add_msg})
            else:
                add_msg = '请输入图书信息!'
                return render(request, 'add_book.html', {'enter_none': add_msg})
Esempio n. 8
0
def search_googlex(request):
    """
    Searches google books for a book with the given barcode (isbn)
    """
    if request.method == 'POST':
        form = BookSearch(request.POST)
        barcode = form.data['barcode']
        response = google_books.search(barcode)
        print "I passed the loop"
        if request.is_ajax():
            print "I think I am ajax"
            json = simplejson.dumps(response)
            return HttpResponse(json, mimetype='application/json')
        return render(
            request, 'search.html', {
                'book_list': response['book_list'],
                'form': form,
                'title': 'Search Google'
            })
    else:
        book = Book(author='a', title='t')
        book.id = 'dummy'
        form = BookSearch()
        return render(
            request,
            'search.html',
            {
                'form': form,
                'title': 'Search Google',
                'book_list': [book]
            },
        )
 def handle(self, *args, **options):
     chunk_size = options.get("chunk")
     bulk_mngr = BulkCreateManager(chunk_size)
     fake = Faker()
     for counter in range(self.NO_OF_SEED_LIBRARY):
         library = Library(name=fake.name() + " Library",
                           updated_at=timezone.now(),
                           archived=False)
         bulk_mngr.add(library)
     bulk_mngr.done()
     library_qs = Library.objects.all()
     print("-- Done creating libraries --")
     for library in library_qs:
         no_of_books_for_library = random.randint(
             self.MIN_NO_OF_BOOKS_PER_LIBRARY,
             self.MAX_NO_OF_BOOKS_PER_LIBRARY)
         print("-- Adding %s books to %s(%s) --" %
               (no_of_books_for_library, library.name, library.id))
         for counter in range(no_of_books_for_library):
             book = Book(title=fake.sentence(),
                         publisher=fake.company(),
                         library=library,
                         updated_at=timezone.now(),
                         archived=False)
             bulk_mngr.add(book)
         bulk_mngr.done()
Esempio n. 10
0
def book(request):

    if request.method == "GET":

        books = Book.objects.all()
        data = []
        for book in books:
            data.append({'url': book.url, 'id': book.id})

        response = HttpResponse(json.dumps(data), mimetype="application/json")
        return response
    elif request.method == "POST":
        #extract data and converts to object
        data = json.loads(request.POST.get('data'))

        #extract the file and the filename
        image = request.FILES['image']
        filename = settings.MEDIA_ROOT + image.name

        #write the file to disk
        with open(filename, 'wb+') as destination:
            for chunk in image.chunks():
                destination.write(chunk)

        book = Book()
        if "description" in data: book.description = data["description"]
        if "category" in data: book.category = data["category"]
        data = book.upload(filename)

        response = HttpResponse(json.dumps(data), mimetype="application/json")
        response.status_code = 201
        return response
Esempio n. 11
0
def upload(request):
    if request.user.is_staff is True:
        if request.method == 'POST':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                newdoc = Book(pdf_file=request.FILES['pdf_file'],
                              title=request.POST['title'],
                              lowercase_title=request.POST['title'].lower(),
                              image=request.FILES['image'])
                newdoc.save()

                # Redirect to the document list after POST
                return HttpResponseRedirect('/upload/')
        else:
            form = UploadFileForm()  # A empty, unbound form

        # Load documents for the list page
        documents = Book.objects.all()

        # Render list page with the documents and the form
        return render(request, 'library/upload.html', {
            'documents': documents,
            'form': form
        })
    else:
        redirect('/')
Esempio n. 12
0
    def handle(self, *args, **options):
        with open('./library/management/commands/words.txt', 'r') as file:
            words = file.read()
        words = words.split('\n')
        for i in range(40):
            random_word = random.choice(words)
            print(f"Searching for book: {random_word}.")
            response = requests.get('http://openlibrary.org/search.json?q=' +
                                    random_word)
            data = json.loads(response.text)
            if len(data['docs']) == 0:
                continue
            book_data = random.choice(data['docs'])
            title = book_data['title']
            if 'first_publish_year' not in book_data:
                continue
            year_published = book_data['first_publish_year']

            authors = book_data.get('author_name',
                                    ['No Author'])  #get or create for this.

            if Book.objects.filter(title=title,
                                   year_published=year_published).exists():
                continue

            book = Book(title=title, year_published=year_published)
            book.save()

            for author in authors:
                author, created = Author.objects.get_or_create(name=author)
                book.authors.add(author)

            print(str(round(i / 40 * 100, 2)) + '%')
Esempio n. 13
0
def new_book():
    if request.method == 'POST':
        book = Book(title=request.form['name'], author=request.form['author'], genre=request.form['genre'])
        session.add(book)
        session.commit()
        return redirect(url_for('show_books'))
    else:
        return render_template('newBook.html')
Esempio n. 14
0
def loadBooks():
    datareader = csv.reader(open('book.csv'), delimiter=',', quotechar='"')
    for row in tqdm(datareader):
        if row[0] != 'ISBN10':
            book = Book()
            book.isbn = row[0]
            book.title = row[1]
            book.save()
Esempio n. 15
0
async def test_query_book(mocker):
    class AsyncMock(MagicMock):
        async def __call__(self, *args, **kwargs):
            return super(AsyncMock, self).__call__(*args, **kwargs)

    book_id = '1'
    double = mocker.patch.object(PostgresPersistence,
                                 'filter',
                                 new_callable=AsyncMock)
    author = Author(name='martin fowler')
    category = Category(title='software engineering')
    book = Book(id=1,
                external_id=book_id,
                title='refactoring',
                subtitle='improving the design of existing code',
                authors=[author],
                categories=[category],
                published_year=1999,
                editor=Editor(name='addison wesley'),
                description='whatever',
                saved=True)

    double.return_value = [book]

    book_DTO = BookDTO(
        external_id=book_id,
        title='refactoring',
        subtitle='improving the design of existing code',
        authors=[{
            'name': 'martin fowler'
        }],
        categories=[{
            'title': 'software engineering'
        }],
        published_year=1999,
        editor={'name': 'addison wesley'},
        description='whatever',
    )
    insert_controller = InsertBookController(data=book_DTO)
    await insert_controller.insert()
    controller = QueryBookController()

    books = await controller.filter(external_id=book_id)

    book = books[0]
    double.assert_called_once_with(external_id=book_id)
    assert book.id
    assert book.external_id == book_id
    assert book.title == 'refactoring'
    assert book.subtitle == 'improving the design of existing code'
    assert book.authors[0].name == 'martin fowler'
    assert book.categories[0].title == 'software engineering'
    assert book.published_year == 1999
    assert book.editor.name == 'addison wesley'
    assert book.description == 'whatever'
    assert book.saved is True
Esempio n. 16
0
    def test_update_book(self):
        john = User.objects.create_user(username='******',
                                        first_name='fjohn',
                                        last_name='ljohn')

        self.assertEqual(john, User.objects.get(id=john.id))

        url = reverse('library:user-detail',
                      kwargs={'username': john.username})

        with open('library/test_img.jpg', 'rb') as fp:
            book = Book(
                author='John Smith',
                title='Python for kids',
                description='This book about python',
                published_year=2013,
                user=john,
            )
            book.poster.save('image_name', fp)
            book.save()
            john.books.add(book)

        self.assertEqual(1, john.books.all().count())
        self.assertEqual(book.slug, 'python-for-kids')
        book = john.books.first()

        # url = book.get_absolute_url()
        url = reverse('library:book-update',
                      kwargs={
                          'id': book.id,
                          'slug': book.slug,
                      })
        self.assertEqual(url, f'/books/{book.id}/python-for-kids/')

        # Data to update book
        with open('library/test_img.jpg', 'rb') as file:
            new_data = {
                'user': john.id,
                'author': 'new author',
                'title': 'Python not for kids',
                'description': 'This book about python',
                'published_year': '2013',
                'poster': file,
                # 'slug': 'python-not-for-kids',
                # 'created': timezone.now(),
            }
            # POST: update book with new data
            resp = self.client.post(url, new_data)

        self.assertEqual(resp.status_code, 302)

        book.refresh_from_db()

        self.assertEqual(book.title, 'Python not for kids')
        self.assertEqual(book.slug, 'python-not-for-kids')
        self.assertEqual(book.author, 'new author')
Esempio n. 17
0
    async def post(self, request):
        # populate the book with the data in the request
        book = Book(**request.json)

        # and await on save
        await book.save()

        return json({'method': request.method,
                     'status': 201,
                     'results': BookSerializer.serialize(book),
                     })
Esempio n. 18
0
def api_book_create(request):
    try:
        author = Author.objects.get(pk=11)
        bkc = Book(author=author)
        if request.method == "POST":
            bk_srl = BookSerializer(bkc, data=request.data)
            if bk_srl.is_valid():
                bk_srl.save()
                return Response(bk_srl.data, status=status.HTTP_201_CREATED)
            return Response(bk_srl.errors, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(e)
Esempio n. 19
0
    async def post(self, request):
        # populate the book with the data in the request
        book = Book(**request.json)

        # and await on save
        await book.save()

        return json({
            "method": request.method,
            "status": 201,
            "results": BookSerializer.serialize(book)
        })
Esempio n. 20
0
    def setUp(self):
        self.author = Author(name='John Doe')
        self.author.save()

        self.category = Category(description='Comedy', )
        self.category.save()

        self.book = Book(title='Any book',
                         author=self.author,
                         category=self.category,
                         pages=900,
                         description='',
                         published_in=datetime.today())
        self.book.save()
def books(request):
    if request.method == "POST":
        title = request.POST['title']
        author = request.POST['author']
        cat = Category.objects.get(id=int(request.POST['category_id']))
        description = request.POST['description']
        available = int(request.POST['quantity'])

        book = Book(title=title, author=author, description=description, available=available)
        book.save()
        if book.categories.add(cat):
            return redirect('/books')
    books = Book.objects.all()
    categories = Category.objects.all()
    return render(request, "books.html", {"books": books, "categories": categories})
Esempio n. 22
0
 async def filter(self, external_id):
     author = Author(name='martin fowler')
     category = Category(title='software engineering')
     book = Book(
         id=1,
         external_id=external_id,
         title='refactoring',
         subtitle='improving the design of existing code',
         authors=[author],
         categories=[category],
         published_year=1999,
         editor=Editor(name='addison wesley'),
         description='whatever',
         saved=True
     )
     return [book]
Esempio n. 23
0
def load():
    f = open('diskBooksData.txt', 'r')
    f.readline()
    for line in f:
        fields = line.rstrip().split('\t')
        b = Book(
            filename=fields[0],
            title=fields[1],
            author=fields[2],
            language=fields[3],
            happs=0.0,
            length=0,
            ignorewords='',
            wiki='http://example.com',
        )
        b.save()
Esempio n. 24
0
    def handle(self, *args, **options):
        with open('library/management/commands/booklist.json', 'r') as books_json:
            text = books_json.read()
        books = json.loads(text)
        for book in books['books']:
            author = book['author']
            title = book['title']
            image = book['image']
            year = book['year']
            pages = book['pages']
            url = book['url']
            country = book['country']
            language = book['language']

            output_book = Book(author=author, title=title, image=image, year=year, pages=pages, url=url, country=country, language=language)
            output_book.save()
Esempio n. 25
0
def new_book():
    form = NewBook()
    if form.validate_on_submit():
        book = Book(id=str(uuid4())[-6:],
                    name=form.name.data,
                    author=form.author.data,
                    description=form.description.data,
                    quantity=form.quantity.data,
                    total_quantity=form.total_quantity.data)
        db.session.add(book)
        db.session.commit()
        flash('Book has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('add_book.html',
                           title='New Book',
                           form=form,
                           legend='New Book')
Esempio n. 26
0
 def handle(self, *args, **options):
     books_csv_paths = options[BOOKS]
     for csv_file_path in books_csv_paths:
         with open(csv_file_path, mode='r', encoding='UTF-8',
                   newline='') as csv_file:
             csv_reader = csv.reader(csv_file, delimiter=';')
             next(csv_reader, None)
             for row in csv_reader:
                 new_book = Book(isnb=row[0],
                                 title=row[1],
                                 author=row[2],
                                 genre=row[3])
                 try:
                     new_book.save()
                 except ValueError as v_err:
                     self.stdout.write(
                         self.style.ERROR(f'Book{row[1]} can not be saved'))
     self.stdout.write(self.style.SUCCESS('Books successfully loaded'))
 def save(self, file_csv):
     records = csv.reader(file_csv)
     next(records)  # skip the first line
     for line in records:
         if len(line) == 7:
             title = line[0]
             author_lf = line[2]
             isbn = line[4] or None
             isbn13 = line[5] or None
             yr_published = line[6] or None
             author = Author.create_from_csv(author_lf)
             book = Book(title=title,
                         isbn=isbn,
                         isbn13=isbn13,
                         year_published=yr_published)
             book.save()
             book.authors = author
             book.save()
Esempio n. 28
0
def create_books(num_entries):
    choices = ['Snake Of The Land', 'Army Of The North', 'Wives Without Glory', 'Priests Of The Prison',
               'Girls And Defenders', 'Slaves And Enemies', 'Wand Of Eternity', 'Spear Without Courage',
               'Meeting At The Future', 'Guarded By My Home', 'God Of The Ancestors', 'Owl Of Next Year',
               'Gods With Money', 'Butchers With Silver', 'Serpents And Witches', 'Serpents And Mice',
               'Murder Of Freedom', 'Love Of The World', 'Blood At The Dark', 'Eating At Myself']
    users = list(User.objects.all())

    for _ in range(num_entries):
        Book(
            name=random.choice(choices),
            author=fake.name(),
            price=fake.random_int(1, 9999),
            pages=fake.random_int(1, 10),
            created_date=fake.date_time_this_month(),
            updated_date=fake.date_time_this_month(),
            rating=fake.random_int(1, 10),
            user=random.choice(users)
        ).save()
Esempio n. 29
0
def book_edit(request, book_id=None):
    """書籍の編集"""
    if book_id:  # book_id が指定されている (修正時)
        book = get_object_or_404(Book, pk=book_id)
    else:  # book_id が指定されていない (追加時)
        book = Book()

    if request.method == 'POST':
        form = BookForm(request.POST,
                        instance=book)  # POST された request データからフォームを作成
        if form.is_valid():  # フォームのバリデーション
            if get_book_info(book):
                book = form.save(commit=False)
                book.save()
                return redirect('library:book_list')
    else:  # GET の時
        form = BookForm(instance=book)  # book インスタンスからフォームを作成

    return render(request, 'library/book_edit.html',
                  dict(form=form, book_id=book_id))
    def handle(self, *args, **options):
        Book.objects.all().delete()

        with open(get_path('books.json'), 'r') as file:
            reader = json.load(file)

            i = 0

            for book in reader:

                book = Book(title=reader[i]['title'],
                            author=reader[i]['author'],
                            description=reader[i]['description'],
                            url=reader[i]['url'],
                            slug=slugify(reader[i]['title']))
                if 'image' in reader[i]:
                    book.image.save(
                        reader[i]['image'],
                        File(open(get_path(reader[i]['image']), 'rb')))
                book.save()
                print(f"Imported {reader[i]['title']}")
                i += 1