async def update_a_book(
    book_id: str,
    book: models.Book,
    response: Response,
    if_match: Optional[str] = Header(None),
) -> Union[Dict[str, Any], Response]:
    book_in_db = await mongo.BACKEND.get_single_book_by_id(book_id=book_id)
    if book_in_db is None:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return {"message": "No such book exist!!"}

    book_details_to_insert = book.dict()

    if if_match is not None and book_in_db.get("eTag") is not None:
        if if_match != book_in_db.get("eTag"):
            return Response(status_code=status.HTTP_412_PRECONDITION_FAILED)

    book_details_to_insert["eTag"] = generate_hash_for_book(book_details_to_insert)

    await mongo.BACKEND.update_one_book(book_id=book_id, data=book_details_to_insert)
    await mongo.BACKEND.insert_authors_in_db(
        string.capwords(book_details_to_insert["author"])
    )
    await mongo.BACKEND.insert_genres_in_db(book_details_to_insert["genres"])

    return await mongo.BACKEND.get_single_book_by_id(book_id=book_id)
Пример #2
0
def register():
    try:
        if not session['logged_in']:
            abort(401)

        form = BookRegistration()

        if request.method == 'GET':
            return render_template('register_book.html', form=form)
            
        req_body = request.form

        if 'copies' not in req_body:
            abort(400, 'Required acquisitions')

        book_dict = {key: value for key, value in req_body.iteritems()
                if key in Book.__table__.columns}
        book = Book(**book_dict).insert()

        db.session.flush()

        for acquisition in req_body['copies'].split():
            copy = BookCopy(acquisition=acquisition, book_id=book.id).insert()
            db.session.flush()
            BookStatus(book_copy_id=copy.id, status='on-shelf').insert()

        db.session.commit()

        return 'Book registered successfully'

    except SQLAlchemyError as error:
        db.session.rollback()
        abort(400, str(error))
Пример #3
0
def new_book():
    b = Book.from_json(request.json)
    db.session.add(b)
    db.session.commit()
    response = jsonify(add_book=b.to_json())
    response.status_code = 200
    return response
Пример #4
0
def add_book():
    data = request.get_json()

    new_book = Book(barcode_id = str(uuid.uuid4()), name = data['name'], tag=False)
    db.session.add(new_book)
    db.session.commit()

    return jsonify({'message': 'Book added!'})
Пример #5
0
def main():
    f = open("books.csv")
    reader = csv.reader(f)
    for isbn, title, author, year in reader:
        book = Book(isbn=isbn, title=title, author=author, year=year)
        db.session.add(book)

    db.session.commit()
Пример #6
0
def home():
    if request.form:
        book_db = Book(book_title=request.form.get("book_title"), author=request.form.get("author"))

        db.session.add(book_db)
        db.session.commit()
    book_lists = Book.query.all()
    return render_template("index.html", book_lists=book_lists)
Пример #7
0
 def setUp(self):
     db.create_all()
     sample = Book(book_title="Shark", author="James")
     sample1 = Users(user_name="bora",
                     user_email="*****@*****.**",
                     start_date="22-02-2021")
     db.session.add(sample)
     db.session.add(sample1)
     db.session.commit()
Пример #8
0
def book_create():
    form = BookForm()

    if request.method == "GET":
        return render_template("bookmarks/book/new.html", form=form)

    prefilled = request.args.get('prefilled')
    form.ISBN.data = re.sub(r'[^\d]*', '', form.ISBN.data)

    if is_valid_isbn(form.ISBN.data):
        if not prefilled:
            try:
                book_details = resolve_book_details(form.ISBN.data)
                form.header.data = book_details.get("title")
                form.writer.data = book_details.get("author")
                form.image.data = book_details.get("image")
                flash('Name and writer resolved successfully, ' +
                      'please check that details are correct')
                return render_template("/bookmarks/book/new.html",
                                       form=form,
                                       prefilled=True)
            except (RuntimeError):
                flash(
                    'Book fetch failed, please give name and title for book yourself'
                )
                return render_template("/bookmarks/book/new.html",
                                       form=form,
                                       prefilled=True)
        else:
            book = Book(header=form.header.data,
                        writer=form.writer.data,
                        comment=form.comment.data,
                        ISBN=form.ISBN.data,
                        image=form.image.data)
    else:
        flash('ISBN given was not valid, please give a valid ISBN instead')
        return render_template("/bookmarks/book/new.html", form=form)

    if form.validate_on_submit():
        db.session().add(book)
        try:
            db.session().commit()
        except IntegrityError:
            db.session.rollback()
            flash('Book with given ISBN was already in the database')
            return render_template("/bookmarks/book/new.html", form=form)

        flash('Book succefully added')
        return redirect(url_for("get_bookmark", bookmark_id=book.id))
    else:
        return render_template("bookmarks/book/new.html", form=form)
Пример #9
0
def show_book():
    books = Book.query.all()

    if request.method == 'POST':
        if not current_user.is_authenticated:
            abort(403)

        title = request.form["title"]
        book = Book(title=title)
        db.session.add(book)
        db.session.commit()
        return redirect(url_for('.show_book'))

    return render_template('book.html', books=books)
Пример #10
0
def new_book():
    form = BookForm()
    if form.validate_on_submit():
        book = Book(isbn=form.isbn.data,
                    title=form.title.data,
                    author=form.author.data,
                    year=form.year.data)
        db.session.add(book)
        db.session.commit()
        flash("Your book has been added to the database.", "success")
        return redirect(url_for('home'))
    return render_template('add_book.html',
                           title='New Book',
                           form=form,
                           legend='New Book')
async def add_a_book(book: models.Book, response: Response) -> Dict[str, Any]:
    book_to_insert = book.dict()
    book_to_insert["book_id"] = str(uuid.uuid1())
    book_to_insert["eTag"] = generate_hash_for_book(book_to_insert)
    book_to_insert["author"] = string.capwords(book_to_insert["author"])

    try:
        await mongo.BACKEND.insert_one_book(data=book_to_insert)
    except mongo.BookExistsException:
        response.status_code = status.HTTP_400_BAD_REQUEST
        return {"message": f"Book {book_to_insert.get('name')} already exists!!"}

    await mongo.BACKEND.insert_authors_in_db(book_to_insert.get("author"))
    await mongo.BACKEND.insert_genres_in_db(book_to_insert.get("genres"))

    get_total_number_of_books.cache_clear()
    return await mongo.BACKEND.get_single_book_by_name(book_to_insert.get("name"))
Пример #12
0
import os
import stripe
from flask import current_app as app, jsonify, flash, redirect, request, make_response
from flask_login import current_user
from flask import render_template
from application import db
from application.bookinfo import books
from application.models import Book, User

for topic in books:
    for book in topic:
        if Book.query.filter_by(name=book["Name"]).first():
            continue
        else:
            databook = Book(book["Name"], book["Author"], book["Summary"], book["Price"], book["Topic"], book["Image"])
            db.session.add(databook)
            db.session.commit()

stripe_keys = {
    "secret_key": os.environ["STRIPE_SECRET_KEY"],
    "publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
}

stripe.api_key = stripe_keys["secret_key"]


@app.route('/')
def home():
    return render_template('home.html', app=app)

Пример #13
0
def register_post():
    # データ取得
    book_name = request.form.get('name')
    series = request.form.get('series')
    vol = request.form.get('vol')
    # all_vol = request.form.get('all-vol')
    error_flag = True

    # バリデーション
    if book_name == '':
        flash('本のタイトルを入力してください')
        return redirect(url_for('books.register'))
    if series and int(vol) < 2:
        flash('有効な数字を入力してください')
        return redirect(url_for('books.register'))
    for i in range(int(vol)):
        form_name = 'vol' + str(i + 1)
        if request.form.get(form_name):
            error_flag = False
    if error_flag:
        flash('持っていない巻を選択してください')
        return redirect(url_for('books.register'))

    # Bookインスタンスの作成
    new_books = []
    if Book.query.all():
        series_id = Book.query.order_by(
            Book.series_id.desc()).first().series_id + 1
    else:
        series_id = 1

    if not series:
        if Book.query.filter_by(book_name=book_name,
                                user_id=current_user.id).first():
            flash('既に追加されています')
            return redirect(url_for('books.register'))
        new_book = Book(series_id=series_id,
                        book_name=book_name,
                        vol=1,
                        user_id=current_user.id)
        new_books.append(new_book)
    else:
        for i in range(int(vol)):
            if Book.query.filter_by(book_name=book_name,
                                    user_id=current_user.id).first():
                flash('既に追加されています')
                return redirect(url_for('books.register'))
            if request.form.get('vol' + str(i + 1)):
                new_book = Book(series_id=series_id,
                                book_name=book_name,
                                vol=i + 1,
                                user_id=current_user.id)
                new_books.append(new_book)

    # Categoriesの追加
    for category in current_user.categories:
        if request.form.get(str(category.category_id)):
            new_books[0].categories.append(category)

    # insert
    try:
        db.session.add_all(new_books)
        db.session.commit()
    except Exception:
        db.session.fallback()
    finally:
        db.session.close()

    return redirect(url_for('books.index'))
Пример #14
0
def edit_post(series_id):
    book_name = request.form.get('name')
    vol = request.form.get('vol')

    # バリデーション
    if not book_name:
        flash('本のタイトルを入力してください')
        return redirect(url_for('books.edit', series_id=series_id))

    error_flag = True
    for i in range(1, int(vol) + 1):
        if request.form.get('vol' + str(i)):
            error_flag = False
    if error_flag:
        flash('持っている巻を選択してください')
        return redirect(url_for('books.edit', series_id=series_id))

    # 更新データの用意
    add_books = []
    if len(
            Book.query.filter_by(series_id=series_id,
                                 user_id=current_user.id).all()) > int(vol):
        i_length = len(
            Book.query.filter_by(series_id=series_id,
                                 user_id=current_user.id).all()) + 1
    else:
        i_length = int(vol) + 1

    for i in range(1, i_length):
        if request.form.get('vol' + str(i)) and i <= int(vol):
            if Book.query.filter_by(series_id=series_id,
                                    vol=i,
                                    user_id=current_user.id).first():
                add_book = Book.query.filter_by(
                    series_id=series_id, vol=i,
                    user_id=current_user.id).first()
                add_book.book_name = book_name
                add_books.append(add_book)
            else:
                add_books.append(
                    Book(book_name=book_name,
                         series_id=series_id,
                         vol=i,
                         user_id=current_user.id))
        else:
            if Book.query.filter_by(series_id=series_id,
                                    vol=i,
                                    user_id=current_user.id).first():
                Book.query.filter_by(series_id=series_id,
                                     vol=i,
                                     user_id=current_user.id).delete()

    add_books[0].categories.clear()
    for category in current_user.categories:
        if request.form.get(str(category.category_id)):
            add_books[0].categories.append(category)

    # update & add
    try:
        db.session.add_all(add_books)
        db.session.commit()
    except Exception:
        db.session.fallback()
    finally:
        db.session.close()

    return redirect(url_for('books.index'))
Пример #15
0
def zongheng_spider(app, url):
    book_id = re.search('\d+', url)
    if book_id is None:
        return
    book_id = book_id.group(0)

    url = 'http://book.zongheng.com/book/{}.html'.format(book_id)

    # extract book detail
    r = requests.get(url)
    if r.status_code != 200:
        return

    soup = BeautifulSoup(r.text, 'lxml')

    cover = soup.find('div', class_='book_cover fl').a.img.get('src')
    bookname = soup.find('div', class_='status fl').h1.a.text
    author = soup.find('div', class_='booksub').find_all('a')[0].text
    tag = soup.find('div', class_='booksub').find_all('a')[1].text
    words = int(soup.find('div', class_='booksub').span.text)
    intro = soup.find('div', class_='info_con').text

    pc_url = 'http://book.zongheng.com/showchapter/{}.html'.format(book_id)

    r = requests.get(pc_url)
    soup = BeautifulSoup(r.text, 'lxml')

    chapters_lists = soup.find_all('td')
    chapter_id = chapters_lists[-1].get('chapterid')
    last_chapter = chapters_lists[-1].get('chaptername')

    r = requests.get('http://book.zongheng.com/chapter/{0}/{1}.html'.format(
        book_id, chapter_id))
    soup = BeautifulSoup(r.text, 'lxml')

    last_update = arrow.get(
        soup.find('span', {
            'itemprop': 'dateModified'
        }).text, 'YY-MM-DD HH:mm:ss')

    with app.app_context():
        book = Book.query.filter_by(pc_url=pc_url).first()

        if book:
            book.cover = cover
            book.chapters = len(chapters_lists)
            book.words = words
            book.last_update = last_update
            book.tag = tag
        else:
            book = Book(
                bookname=bookname,
                author=author,
                tag=tag,
                intro=intro,
                chapters=len(chapters_lists),
                words=words,
                last_update=last_update,
                last_chapter=last_chapter,
                cover=cover,
                source='纵横中文网',
                pc_url=pc_url,
                m_url='https://m.zongheng.com/h5/book?bookid={}'.format(
                    book_id))
            db.session.add(book)
        db.session.commit()
Пример #16
0
def qidian_spider(app, url):
    book_id = re.search('\d+', url)
    if book_id is None:
        return
    book_id = book_id.group(0)

    # crawl the mobile page
    url = 'https://m.qidian.com/book/' + book_id

    # extract book detail
    r = requests.get(url)
    if r.status_code != 200:
        return

    soup = BeautifulSoup(r.text, 'lxml')

    cover = soup.find('div', class_='book-layout').img.get('src')
    bookname = soup.find('h2', class_='book-title').text
    author = soup.find('h4', class_='book-title').text
    tag = soup.find('p', class_='book-meta').text
    intro = soup.find('content').text

    # use api to get chapter details
    r = requests.get('https://book.qidian.com/ajax/book/category?bookId=' +
                     book_id)
    r.encoding = 'utf-8'
    results = json.loads(r.text)

    if results['code']:
        return

    total_chapters = results['data']['chapterTotalCnt']
    total_words = 0
    last_update = arrow.get(
        results['data']['vs'][-1]['cs'][-1]['uT'],
        'YYYY-MM-DD HH:mm:ss').replace(tzinfo='Asia/Shanghai')
    last_chapter = results['data']['vs'][-1]['cs'][-1]['cN']

    # count total words
    for volume in results['data']['vs']:
        for c in volume['cs']:
            total_words += c['cnt']

    pc_url = 'http://book.qidian.com/info/{}#Catalog'.format(book_id)

    with app.app_context():
        book = Book.query.filter_by(pc_url=pc_url).first()

        if book:
            book.cover = cover
            book.chapters = total_chapters
            book.words = total_words
            book.last_update = last_update
            book.tag = tag
        else:
            book = Book(bookname=bookname,
                        author=author,
                        tag=tag,
                        intro=intro,
                        chapters=total_chapters,
                        words=total_words,
                        last_update=last_update,
                        last_chapter=last_chapter,
                        cover=cover,
                        source='起点中文网',
                        pc_url=pc_url,
                        m_url=url)
            db.session.add(book)
        db.session.commit()