Exemplo n.º 1
0
 def post(self, book_id):
     """Post method for user to borrow book"""
     available_book = Book.query.filter_by(book_id=book_id).first()
     has_borrowed_book = Borrow.query.filter_by(
         book_id=book_id, user_id=get_jwt_identity()).first()
     date_borrowed = datetime.datetime.now()
     due_date = datetime.datetime.now() + datetime.timedelta(days=14)
     if available_book.copies >= 1:
         if has_borrowed_book:
             return {
                 "message":
                 "You have borrowed this book previously and can't borrow until returned"
             }, 403
         books_borrowed = user_un_returned_books()
         if len(books_borrowed) > 3:
             return {"message": "You can borrow only up to 3 books."}, 403
         borrow_book = Borrow(borrow_id=random.randint(1111, 9999),
                              book_id=book_id,
                              user_id=get_jwt_identity(),
                              returned=False,
                              date_borrowed=date_borrowed,
                              due_date=due_date)
         available_book.copies -= 1
         borrow_book.save_borrowed_book()
         result = borrow_book.borrow_serializer()
         return {"book_borrowed": result}, 200
     return {"message": "The book is not available for borrow."}, 404
Exemplo n.º 2
0
    def post(self, id):
        """ This method borrows a single book"""
        try:
            id = int(id)
        except ValueError:
            return jsonify({"Message": "Invalid book ID"}), 404
        book = Book.query.filter_by(id=id).first()
        if book:
            if book.availabilty is True:
                borrow_book = Borrow(user_email=g.user.email,
                                     book_id=id,
                                     returned=False)
                book.availabilty = False
                db.session.add(borrow_book)
                db.session.commit()
                return make_response(
                    jsonify({
                        "Message":
                        "You have borrowed "
                        "a book with id {}".format(id)
                    }), 200)

            else:
                return make_response(
                    jsonify({
                        "Message":
                        "The book is not available at "
                        "the moment"
                    }), 400)
        else:
            return make_response(jsonify({"Message": "No book with that id"}),
                                 400)
Exemplo n.º 3
0
def user_borrow_book():
    global res
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    card = db.session.query(Card).filter_by(user_id=current_user.id).first()
    if check_user() != '':
        return redirect(url_for(check_user()))
    if card == None:
        flash(
            'You have not got a borrow card. Your id is {}, ask the admin to create a card for this id.'
            .format(current_user.id))
        return redirect(url_for('index'))
    form = FindBookForm()
    form2 = BorrowBookForm()
    if form.submit1.data and form.validate_on_submit():
        if form.mul.data == 1:
            res = db.session.query(Book).filter_by(
                bookname=form.context.data).all()
        elif form.mul.data == 2:
            res = db.session.query(Book).filter_by(
                author=form.context.data).all()
        elif form.mul.data == 3:
            res = db.session.query(Book).filter_by(
                type=form.context.data).all()
        else:
            res = db.session.query(Book).filter_by(
                year=int(form.context.data)).all()
    form2.mul.choices = [(book.id, book.bookname) for book in res]
    nonexistbook = []
    cannotborrow = []
    success = []
    if form2 and form2.submit2.data and form2.validate_on_submit():
        for bid in form2.mul.data:
            book = db.session.query(Book).filter_by(id=bid).first()
            if book is None:
                nonexistbook.append(book.bookname + ' ')
            elif card.borrow_num == 0:
                cannotborrow.append(book.bookname + ' ')
            else:
                card.borrow_num -= 1
                book.remain -= 1
                success.append(book.bookname + ' ')
                record = Borrow(book_id=book.id, user_id=current_user.id)
                db.session.add(record)
        if success != []:
            flash('Succeed to borrow books: {}'.format(''.join(success)))
        if nonexistbook != []:
            flash('Fail to borrow books for lack of remains in library: {}'.
                  format(''.join(nonexistbook)))
        if cannotborrow != []:
            flash(
                'Fail to borrow books for disability of your card: {}'.format(
                    ''.join(cannotborrow)))
        db.session.commit()
    return render_template('user_borrow_book.html',
                           form=form,
                           form2=form2,
                           res=res)
Exemplo n.º 4
0
def book_borrowings(book_id):
    error = None
    book = Book.query.get(book_id)
    borrows = [borrow for borrow in book.borrows]
    if len(borrows) != 0:
        latest = book.borrows[-1]
    else:
        latest = None
    form = BorrowForm()
    if request.method == "POST":
        if form.data['in_stock'] == "Wypożyczam":
            if (latest is None) or (latest.in_stock is True):
                borrow = Borrow(in_stock=False, book=book)
                db.session.add(borrow)
                db.session.commit()

            else:
                error = 'Nie możesz wypożyczyć tej książki'
                return render_template("book.html",
                                       book=book,
                                       form=form,
                                       borrows=borrows,
                                       error=error)

        elif form.data['in_stock'] == "Oddaję":
            if (latest is None) or (latest.in_stock is False):
                borrow = Borrow(in_stock=True, book=book)
                db.session.add(borrow)
                db.session.commit()
            else:
                error = 'Nie możesz oddać tej książki'
                return render_template("book.html",
                                       book=book,
                                       form=form,
                                       borrows=borrows,
                                       error=error)

        return redirect(url_for('.book_borrowings', book_id=book_id))

    return render_template("book.html",
                           book=book,
                           form=form,
                           borrows=borrows,
                           error=error)
Exemplo n.º 5
0
def books_list():
    form = BookForm()
    books = Book.query.all()
    authors_names = [author.name for author in Author.query.all()]
    error = None
    if request.method == "POST":
        title = form.data['title']
        authors = [
            form.data['author1'], form.data['author2'], form.data['author3']
        ]
        # set default value for a new book on 'in_stock'
        status = form.data['status']
        if title not in [book.title for book in books]:
            book = Book(title=title)
            borrow = Borrow(in_stock=status, book=book)
            db.session.add(book)
            db.session.add(borrow)
            db.session.commit()
            for author in authors:
                if author == '':
                    pass
                elif author in authors_names:
                    for a in Author.query.filter_by(name=author):
                        if a.name == author:
                            book.authors.append(a)
                            db.session.commit()
                        else:
                            pass
                elif author not in authors_names:
                    author = Author(name=author)
                    book.authors.append(author)
                    db.session.commit()
        else:
            error = "Książka o tym tytule istnieje już w bazie. " \
                    "Jeśli to inna książka, dodaj szczegół, " \
                    "np. rok wydania, aby je odróżnić."
            return render_template("books.html",
                                   books=books,
                                   form=form,
                                   error=error)

        return redirect(url_for("books_list"))

    return render_template("books.html", books=books, form=form, error=error)
Exemplo n.º 6
0
def author_books(author_id):
    author = Author.query.get(author_id)
    books = author.books
    all_titles = [book.title for book in Book.query.all()]
    form = BookForm()
    error = None
    if request.method == "POST":
        title = form.data['title']
        """An author does not typically write two books of the same title,
        if they do, they must be distinguished manually"""
        if title in all_titles:
            book = [book for book in Book.query.filter_by(title=title)][0]
            if author in book.authors:
                error = "Ta książka już istnieje w bazie."
                return render_template("author.html",
                                       author=author,
                                       books=books,
                                       form=form,
                                       error=error)
            # title exists, but the other author is missing
            else:
                author.books.append(book)
                db.session.commit()
        # most typical case: just enter some new title
        else:
            book = Book(title=title)
            """set default value for a new book on in_stock,
            there could be choice like in the /books/ routing
            (just to show you I can do it, enter a new book borrowed,
            which is silly) but have merci,
            I'm almost dead of this exi."""
            borrow = Borrow(in_stock=True, book=book)
            db.session.add(book)
            db.session.add(borrow)
            author.books.append(book)
            db.session.commit()

        return redirect(url_for('.author_books', author_id=author_id))

    return render_template("author.html",
                           author=author,
                           books=books,
                           form=form,
                           error=error)
Exemplo n.º 7
0
def borrow_add():
    """
    借阅书籍
    """
    books_id = request.args.get("books_id", "")  # 接收传递的参数books_id
    user_id = session['user_id']  # 获取当前用户的ID
    borrow = Borrow.query.filter_by(  # 根据用户ID和书籍ID判断是否借阅
        user_id=int(user_id), books_id=int(books_id)).count()
    # 已订阅
    if borrow == 1:
        data = dict(ok=0)  # 写入字典
    # 未订阅进行订阅
    if borrow == 0:
        borrow = Borrow(user_id=int(user_id), books_id=int(books_id))
        db.session.add(borrow)  # 添加数据
        db.session.commit()  # 提交数据
        data = dict(ok=1)  # 写入字典
    import json  # 导入模块
    return json.dumps(data)  # 返回json数据
Exemplo n.º 8
0
def borrow_book():
    user_id = int(request.get_json().get("user_id"))
    book_id = int(request.get_json().get("book_id"))
    book = Book.query.get_or_404(book_id)
    borrow_date = datetime.utcnow() + timedelta(hours=8)
    return_date = borrow_date + timedelta(days=90)
    status = 1
    days = 90
    borrow = Borrow(borrow_date=borrow_date,
                    return_date=return_date,
                    days=days,
                    status=status,
                    user_id=user_id,
                    book_id=book_id)
    db.session.add(borrow)
    db.session.commit()
    book.borrowtime = book.borrowtime + 1
    db.session.add(book)
    db.session.commit()
    return jsonify({"borrow_id": borrow.id})