示例#1
0
    def add_book():
        # Метод для добавления новой книги.
        # Информация о коллекция выбирается автоматически из коллекций, принадлежащих пользователю.
        # Из-за того, что в RadioField находится только индекс выбранного элемента, выбор коллекции производится вручную
        form = BookForm()

        db_sess = db_session.create_session()
        if current_user.is_authenticated:
            collections = db_sess.query(Collection).filter((Collection.user == current_user))
        else:
            collections = []

        index = form.collection_id.data

        if request.method == "POST" and form.validate_on_submit():
            db_sess = db_session.create_session()
            book = Book()
            book.title = form.title.data
            book.author = form.author.data
            book.opinion = form.opinion.data
            book.year = form.year.data
            book.is_private = form.is_private.data
            if index is not None:
                book.collection_id = collections[int(index) - 1].id
            current_user.books.append(book)
            db_sess.merge(current_user)
            db_sess.commit()
            return redirect('/books')

        choices = []
        for item in collections:
            choices.append((item.id, item.name))
        form.collection_id.choices = choices

        return render_template('add_book.html', title='Добавление книги', form=form, collections=collections.count())
示例#2
0
def add_book():
    form = BookForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        book = Book()
        book.title = form.title.data
        book.author = form.author.data
        genre = db_sess.query(Genre).filter(Genre.title == form.genre.data).first()
        if not genre:
            new_genre = Genre(title=form.genre.data)
            db_sess.add(new_genre)
            db_sess.commit()
            genre = db_sess.query(Genre).filter(Genre.title == form.genre.data).first()
        book.genre = genre
        book.created_date = form.created_date.data
        book.annotation = form.annotation.data
        book.img_file = form.img_file.data.filename
        print(form.img_file.data)
        print(type(form.img_file.data))
        form.img_file.data.save(f'static/img/{form.img_file.data.filename}')
        book.text_file = form.text_file.data.filename
        form.text_file.data.save(f'static/text/{form.text_file.data.filename}')
        genre.book.append(book)
        db_sess.merge(genre)
        db_sess.commit()
        return redirect('/')
    return render_template('book.html', title='Добавление книги', form=form)
示例#3
0
def add_book():
    form = BookForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        book = Books()
        book.title = form.title.data
        book.pic_url = form.pic_url.data
        book.author = form.author.data
        book.content = form.content.data
        book.file_name = form.file.data.filename
        book.marked_file_name = f"marked_{form.file.data.filename}"
        form.file.data.save(os.path.join(
            app.auto_find_instance_path(), form.file.data.filename))
        current_user.books.append(book)
        db_sess.merge(current_user)
        db_sess.commit()
        book_load(os.path.join(
            app.auto_find_instance_path(), form.file.data.filename), f'{book.file_name}')
        path = os.path.join(
            app.auto_find_instance_path(), form.file.data.filename)
        path2 = os.path.join(
            app.auto_find_instance_path(), f'{book.marked_file_name}.csv')
        if marking(book.file_name, path, path2):
            book_load(os.path.join(
                app.auto_find_instance_path(), f'{book.marked_file_name}.csv'), f'{book.marked_file_name}.csv')
        os.remove(os.path.join(
            app.auto_find_instance_path(), book.file_name))
        os.remove(os.path.join(
            app.auto_find_instance_path(), f'{book.marked_file_name}.csv'))
        disk.publish(f"/book/{book.file_name}")
        disk.publish(f"/book/{book.marked_file_name}.csv")
        return redirect('/')
    return render_template('books.html', file_label='Файл книги (.txt)', title='Добавление книги',
                           form=form)
示例#4
0
def edit_book(id):
    form = BookForm()
    if request.method == "GET":
        db_sess = db_session.create_session()
        book = db_sess.query(Books).filter(Books.id == id,
                                           Books.user == current_user
                                           ).first()
        if book:
            form.title.data = book.title
            form.author.data = book.author
            form.pic_url.data = book.pic_url
            form.content.data = book.content
        else:
            abort(404)
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        book = db_sess.query(Books).filter(Books.id == id,
                                           Books.user == current_user
                                           ).first()
        if book:
            book.title = form.title.data
            book.author = form.author.data
            book.pic_url = form.pic_url.data
            book.content = form.content.data
            if book.file_name != form.file.data.filename:
                disk.remove(f"/book/{book.file_name}")
                disk.remove(f"/book/{book.marked_file_name}.csv")
                book.file_name = form.file.data.filename
                book.marked_file_name = f"marked_{form.file.data.filename}"
                form.file.data.save(os.path.join(
                    app.auto_find_instance_path(), form.file.data.filename))
                book_load(os.path.join(
                    app.auto_find_instance_path(), form.file.data.filename), f'{book.file_name}')
                path = os.path.join(
                    app.auto_find_instance_path(), form.file.data.filename)
                path2 = os.path.join(
                    app.auto_find_instance_path(), f'{book.marked_file_name}.csv')
                if marking(book.file_name, path, path2):
                    book_load(os.path.join(
                        app.auto_find_instance_path(), f'{book.marked_file_name}.csv'), f'{book.marked_file_name}.csv')
                os.remove(os.path.join(
                    app.auto_find_instance_path(), book.file_name))
                os.remove(os.path.join(
                    app.auto_find_instance_path(), f'{book.marked_file_name}.csv'))
                disk.publish(f"/book/{book.file_name}")
                disk.publish(f"/book/{book.marked_file_name}.csv")
            db_sess.commit()
            return redirect('/')
        else:
            abort(404)
    return render_template('books.html',
                           title='Редактирование новости',
                           form=form
                           )
示例#5
0
    def edit_books(id):
        # Метод для редактирования книги.
        # Информация о коллекция выбирается автоматически из коллекций, принадлежащих пользователю.
        # Из-за того, что в RadioField находится только индекс выбранного элемента, выбор коллекции производится вручную
        db_sess = db_session.create_session()
        if current_user.is_authenticated:
            collections = db_sess.query(Collection).filter((Collection.user == current_user))
        else:
            collections = []
        form = BookForm()
        if request.method == "GET":
            db_sess = db_session.create_session()
            book = db_sess.query(Book).filter(Book.id == id,
                                              Book.user == current_user).first()
            choices = []
            for item in collections:
                choices.append((item.id, item.name))
            form.collection_id.choices = choices

            if book:
                form.title.data = book.title
                form.author.data = book.author
                form.opinion.data = book.opinion
                form.year.data = book.year
                if book.collection_id is not None:
                    index = 0
                    for col in collections:
                        index += 1
                        if col.id == book.collection_id:
                            form.collection_id.data = str(index)
                form.is_private.data = book.is_private
            else:
                abort(404)
        if request.method == "POST" and form.validate_on_submit():
            db_sess = db_session.create_session()
            book = db_sess.query(Book).filter(Book.id == id,
                                              Book.user == current_user).first()
            index = form.collection_id.data
            if book:
                book.title = form.title.data
                book.author = form.author.data
                book.opinion = form.opinion.data
                book.year = form.year.data
                book.is_private = form.is_private.data
                if index is not None:
                    book.collection_id = collections[int(index) - 1].id
                db_sess.commit()
                return redirect('/books')
            else:
                abort(404)
        return render_template('edit_book.html', title='Редактирование книги', form=form,
                               collections=collections.count())
示例#6
0
def test_update_book(view_edit_book, client, login_form_admin_credentials,
                     mock_ldap):
    with mock.patch('views.index.ldap_client', mock_ldap):
        languages = ['polish', 'english', 'other']
        categories = ['developers', 'managers', 'magazines', 'other']
        g = Generic('en')

        item = LibraryItem.query.filter_by(
            title=view_edit_book.title.data).first()

        form = BookForm(radio='book',
                        first_name=g.person.name(),
                        surname=g.person.surname(),
                        title=' '.join(g.text.title().split(' ')[:3]),
                        table_of_contents=g.text.sentence(),
                        language=choice(languages),
                        category=choice(categories),
                        tag=g.text.words(1),
                        description=g.text.sentence(),
                        isbn=str(9789295055025),
                        original_title=' '.join(g.text.title().split(' ')[:3]),
                        publisher=g.business.company(),
                        pub_date=str(randint(1970, 2018)))
        client.post(url_for('library.login'),
                    data=login_form_admin_credentials.data)
        client.post(url_for('library_books.edit_book', item_id=item.id),
                    data=form.data,
                    follow_redirects=True)
        tmp_item = LibraryItem.query.filter_by(id=item.id).first()

        assert tmp_item.title == form.title.data, \
            "Book title has not been updated"
        assert tmp_item.authors[0].first_name == form.first_name.data, \
            "Authors first name has not been updated"
        assert tmp_item.authors[0].last_name == form.surname.data, \
            "Authors last name not been updated"
        assert tmp_item.table_of_contents == form.table_of_contents.data, \
            "Book table of contents has not been updated"
        assert tmp_item.language == form.language.data, \
            "Book language has not been updated"
        assert tmp_item.category == form.category.data, \
            "Book category has not been updated"
        assert tmp_item.description == form.description.data, \
            "Book description has not been updated"
        assert tmp_item.isbn == form.isbn.data, \
            "Book isbn has not been updated"
        assert tmp_item.original_title == form.original_title.data, \
            "Book original_title has not been updated"
        assert tmp_item.publisher == form.publisher.data, \
            "Book publisher has not been updated"
        assert tmp_item.pub_date == datetime.date(
            year=int(form.pub_date.data), month=1,
            day=1), "Book pub_date has not been updated"
        assert tmp_item.tags[0].name == form.tag.data[0], \
            "Book tags has not been updated"
        session.clear()
示例#7
0
def edit_book(book_id):
    form = BookForm()
    if request.method == "GET":
        db_sess = db_session.create_session()
        book = db_sess.query(Book).filter(Book.id == book_id).first()
        if book:
            form.title.data = book.title
            form.author.data = book.author
            genre = db_sess.query(Genre).filter(Genre.id == book.genre_id).first()
            form.genre.data = genre.title
            form.created_date.data = book.created_date
            form.annotation.data = book.annotation
        else:
            abort(404)
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        book = db_sess.query(Book).filter(Book.id == book_id).first()
        if book:
            book.title = form.title.data
            book.author = form.author.data
            genre = db_sess.query(Genre).filter(Genre.title == form.genre.data).first()
            if not genre:
                new_genre = Genre(title=form.genre.data)
                db_sess.add(new_genre)
                db_sess.commit()
                genre = db_sess.query(Genre).filter(Genre.title == form.genre.data).first()
            book.genre_id = genre.id
            book.created_date = form.created_date.data
            book.annotation = form.annotation.data
            book.img_file = form.img_file.data.filename
            form.img_file.data.save(f'static/img/{form.img_file.data.filename}')
            book.text_file = form.text_file.data.filename
            form.text_file.data.save(f'static/text/{form.text_file.data.filename}')
            db_sess.commit()
            return redirect('/')
        else:
            abort(404)
    return render_template('book.html',
                           title='Редактирование книги',
                           form=form
                           )
示例#8
0
def add_book():
    form = BookForm()
    session = db_session.create_session()
    form.categories.choices = [
        (category.id, category.name)
        for category in session.query(Category).order_by(Category.name).all()
    ]
    if form.validate_on_submit():
        user = session.query(User).get(current_user.id)

        # noinspection PyArgumentList
        book = Book(title=form.title.data,
                    description=form.description.data,
                    price=form.price.data,
                    stock=form.stock.data,
                    release_date=form.release_date.data)

        if form.is_user_author:
            author = session.query(Author).get(user.author_id)
            if not author:
                # noinspection PyArgumentList
                author = Author(first_name=current_user.first_name,
                                last_name=current_user.last_name)
                user.author = author
            book.author = author
        # Save image and/or book file to server if provided
        if form.image.data:
            image_path = resize_and_save_image(form.image.data.filename)
            book.image_path = image_path
        if form.content.data:
            file_path = save_file(form.content.data.filename)
            book.file_path = file_path
        session.merge(book)
        session.commit()
        return redirect('/')
    return render_template('add_book.html',
                           title='Add book',
                           form=form,
                           header='Add book')
示例#9
0
def view_edit_book(session):
    languages = ['polish', 'english', 'other']
    categories = ['developers', 'managers', 'magazines', 'other']

    author = Author(first_name=g.person.name(), last_name=g.person.surname())
    session.add(author)

    tag = Tag(name=g.text.words(1))
    session.add(tag)
    session.commit()
    form = BookForm(radio='book',
                    first_name=author.first_name,
                    surname=author.last_name,
                    title=' '.join(g.text.title().split(' ')[:3]),
                    table_of_contents=g.text.sentence(),
                    language=choice(languages),
                    category=choice(categories),
                    tag=tag.name,
                    description=g.text.sentence(),
                    isbn=str(9789295055025),
                    original_title=' '.join(g.text.title().split(' ')[:3]),
                    publisher=g.business.company(),
                    pub_date=str(randint(1970, 2018)))

    book = Book(title=form.title.data,
                authors=[author],
                table_of_contents=form.table_of_contents.data,
                language=form.language.data,
                category=form.category.data,
                tags=[tag],
                description=form.description.data,
                isbn=form.isbn.data,
                original_title=form.original_title.data,
                publisher=form.publisher.data,
                pub_date=datetime(year=int(form.pub_date.data), month=1,
                                  day=1))

    session.add(book)
    session.commit()

    return form
示例#10
0
def view_book(session, client):
    languages = ['polish', 'english', 'other']
    categories = ['developers', 'managers', 'magazines', 'other']
    type_book = ['book', 'magazine']

    form = BookForm(radio=choice(type_book),
                    first_name=g.person.name(),
                    surname=g.person.surname(),
                    title=' '.join(g.text.title().split(' ')[:5]),
                    title_of_magazine=' '.join(g.text.title().split(' ')[:5]),
                    table_of_contents=g.text.sentence(),
                    language=choice(languages),
                    category=choice(categories),
                    tag=g.text.words(1),
                    description=g.text.sentence(),
                    isbn=str(1861972717),
                    original_title=' '.join(g.text.title().split(' ')[:5]),
                    publisher=g.business.company(),
                    pub_date=str(randint(1970, 2018)),
                    issue=g.text.words(1))

    yield form
示例#11
0
def add_book():
    if request.method == 'GET':
        if 'logged_in' not in session:
            message_body = 'You are not logged in.'
            message_title = 'Error!'
            return render_template('message.html',
                                   message_title=message_title,
                                   message_body=message_body)
        else:
            form = BookForm()

        return render_template('add_book.html',
                               form=form,
                               error=form.errors)
    else:
        form = BookForm()
        if form.radio.data == 'book':
            del form.issue
            del form.title_of_magazine
            if form.validate_on_submit():
                tmp_authors = [[form.first_name.data, form.surname.data],
                               [form.first_name_1.data, form.surname_1.data],
                               [form.first_name_2.data, form.surname_2.data],
                               ]

                new_authors = []

                for first_name, surname in tmp_authors:
                    if first_name is not '' and surname is not '':
                        author = Author.query.filter_by(first_name=first_name,
                                                        last_name=surname
                                                        ).first()
                        if not author:
                            new_author = Author(
                                first_name=first_name,
                                last_name=surname
                            )
                            new_authors.append(new_author)
                            db.session.add(new_author)
                            db.session.commit()
                        else:
                            new_authors.append(author)

                tmp_tag = Tag.query.filter_by(name=form.tag.data).first()
                if not tmp_tag:
                    new_tag = Tag(
                        name=form.tag.data
                    )
                    db.session.add(new_tag)
                    db.session.commit()
                else:
                    new_tag = tmp_tag

                new_book = Book(
                    title=form.title.data,
                    table_of_contents=form.table_of_contents.data,
                    language=form.language.data,
                    category=form.category.data,
                    tags=[new_tag],
                    description=form.description.data,
                    isbn=form.isbn.data,
                    authors=new_authors,
                    original_title=form.original_title.data,
                    publisher=form.publisher.data,
                    pub_date=datetime(year=int(form.pub_date.data),
                                      month=1,
                                      day=1))
                if book_exists(new_book):
                    message_body = 'This book already exists.'
                    message_title = 'Oops!'
                    return render_template('message.html',
                                           message_title=message_title,
                                           message_body=message_body)
                db.session.add(new_book)
                db.session.commit()

                message_body = 'The book has been added.'
                message_title = 'Success!'
                return render_template('message.html',
                                       message_title=message_title,
                                       message_body=message_body)

            return render_template('add_book.html',
                                   form=form,
                                   error=form.errors)

        if form.radio.data == 'magazine':
            del form.publisher
            del form.original_title
            del form.isbn
            del form.title
            if form.validate_on_submit():

                tmp_tag = Tag.query.filter_by(name=form.tag.data).first()
                if not tmp_tag:
                    new_tag = Tag(
                        name=form.tag.data
                    )
                    db.session.add(new_tag)
                    db.session.commit()
                else:
                    new_tag = tmp_tag

                new_magazine = Magazine(
                    title=form.title_of_magazine.data,
                    table_of_contents=form.table_of_contents.data,
                    language=form.language.data,
                    category=form.category.data,
                    tags=[new_tag],
                    description=form.description.data,
                    year=datetime(year=int(form.pub_date.data),
                                  month=1,
                                  day=1),
                    issue=form.issue.data)

                db.session.add(new_magazine)
                db.session.commit()

                message_body = 'The magazine has been added.'
                message_title = 'Success!'
                return render_template('message.html',
                                       message_title=message_title,
                                       message_body=message_body)

            return render_template('add_book.html',
                                   form=form,
                                   error=form.errors)
示例#12
0
def create_get_form(item):
    authors_list = item.authors
    if len(authors_list) == 1:
        form = BookForm(title=item.title,
                        table_of_contents=item.table_of_contents,
                        language=item.language,
                        category=item.category,
                        tag=item.tags_string,
                        description=item.description,
                        isbn=item.isbn,
                        original_title=item.original_title,
                        publisher=item.publisher,
                        pub_date=item.pub_date,
                        first_name=authors_list[0].first_name,
                        surname=authors_list[0].last_name)

    elif len(authors_list) == 2:
        form = BookForm(title=item.title,
                        table_of_contents=item.table_of_contents,
                        language=item.language,
                        category=item.category,
                        tag=item.tags_string,
                        description=item.description,
                        isbn=item.isbn,
                        original_title=item.original_title,
                        publisher=item.publisher,
                        pub_date=item.pub_date,
                        first_name=authors_list[0].first_name,
                        surname=authors_list[0].last_name,
                        first_name_1=authors_list[1].first_name,
                        surname_1=authors_list[1].last_name)

    elif len(authors_list) == 3:
        form = BookForm(title=item.title,
                        table_of_contents=item.table_of_contents,
                        language=item.language,
                        category=item.category,
                        tag=item.tags_string,
                        description=item.description,
                        isbn=item.isbn,
                        original_title=item.original_title,
                        publisher=item.publisher,
                        pub_date=item.pub_date,
                        first_name=authors_list[0].first_name,
                        surname=authors_list[0].last_name,
                        first_name_1=authors_list[1].first_name,
                        surname_1=authors_list[1].last_name,
                        first_name_2=authors_list[2].first_name,
                        surname_2=authors_list[2].last_name)
    else:
        form = BookForm(title=item.title,
                        table_of_contents=item.table_of_contents,
                        language=item.language,
                        category=item.category,
                        tag=item.tags_string,
                        description=item.description,
                        isbn=item.isbn,
                        original_title=item.original_title,
                        publisher=item.publisher,
                        pub_date=item.pub_date)
    return form
示例#13
0
def edit_book(item_id):
    if request.method == 'GET':
        try:
            user = User.query.get(session['id'])
            user.has_role('ADMIN')
        except KeyError:
            abort(401)
        except Exception:
            abort(500)

        item = LibraryItem.query.get_or_404(item_id)

        if item.type == 'book':
            form = create_get_form(item)
            return render_template('edit_book.html',
                                   form=form,
                                   error=form.errors,
                                   item_type=item.type)

        elif item.type == 'magazine':
            form = MagazineForm(title_of_magazine=item.title,
                                issue=item.issue,
                                table_of_contents=item.table_of_contents,
                                language=item.language,
                                category=item.category,
                                tag=item.tags_string,
                                description=item.description,
                                pub_date=item.year)

            return render_template('edit_book.html',
                                   form=form,
                                   error=form.errors,
                                   item_type=item.type)

    else:

        item = LibraryItem.query.get_or_404(item_id)
        if item.type == 'book':
            form = BookForm(radio='book')
            to_validate = check_diff_book(form, item)
            for i in to_validate:
                i.validate(form)

            if not form.errors:
                update_book(form, item)
                message_body = 'The book has been updated.'
                message_title = 'Success!'
                return render_template('message.html',
                                       message_title=message_title,
                                       message_body=message_body)

            return render_template('edit_book.html',
                                   item_id=item.id,
                                   item_type=item.type,
                                   form=form,
                                   error=form.errors)
        if item.type == 'magazine':
            form = MagazineForm(radio='magazine')

            to_validate = check_diff_magazine(form, item)
            for i in to_validate:
                i.validate(form)

            if not form.errors:
                update_magazine(form, item)

                message_body = 'The magazine has been updated.'
                message_title = 'Success!'
                return render_template('message.html',
                                       message_title=message_title,
                                       message_body=message_body)

            return render_template('edit_book.html',
                                   item_id=item.id,
                                   item_type=item.type,
                                   form=form,
                                   error=form.errors)
        else:
            message_body = 'Oops something went wrong'
            message_title = 'Error!'
            return render_template('message.html',
                                   message_title=message_title,
                                   message_body=message_body)