Ejemplo n.º 1
0
 def create(self):
     self.book = Book(self.input('book'))
     if self.book.save():
         self.redirect_to(action="index")
     else:
         self.subjects = Subject.find("all")
         self.render("new")
Ejemplo n.º 2
0
def add_new_book():
    name = request.form.get('name')
    author_id = request.form.get('author_id')
    category_id = request.form.get('category_id')
    isbn = request.form.get('isbn')
    content = request.form.get('content')
    file = request.files['image_url']
    if file and allowed_file(file.filename):
        file_name = rename_for_upload(file.filename)
        # 注意:没有的文件夹一定要先创建,不然会提示没有该路径(一定要相对路径)
        upload_path = os.path.join('static/uploads/', file_name)
        file.save(upload_path)
        book = Book()
        book.name = name
        book.author_id = author_id
        book.category_id = category_id
        book.isbn = isbn
        book.content = content
        book.image_url = upload_path
        try:
            book.save()
            return CreateSuccess()
        except:
            return ParameterError()
    else:
        return ParameterError()
Ejemplo n.º 3
0
def two_saved_books(app):
    ocean_book = Book(title="Ocean Book", description="watr 4evr")
    mountain_book = Book(title="Mountain Book",
                         description="i luv 2 climb rocks")

    db.session.add_all([ocean_book, mountain_book])
    db.session.commit()
Ejemplo n.º 4
0
def add_new():
    # 使用form重写添加书籍函数,使用form可以直接验证数据字段是否提交
    form = BookAddForm(request.form).validate_for_api()
    name = form.name.data
    author_id = form.author_id.data
    category_id = form.category_id.data
    isbn = form.isbn.data
    content = form.content.data
    # image_url 字段通过request获取
    file = request.files['image_url']
    if file and allowed_file(file.filename):
        file_name = rename_for_upload(file.filename)
        upload_path = os.path.join('static/uploads/', file_name)
        file.save(upload_path)
        book = Book()
        book.name = name
        book.author_id = author_id
        book.category_id = category_id
        book.isbn = isbn
        book.content = content
        book.image_url = upload_path
        book.save()
        return CreateSuccess()
    else:
        return ParameterError()
Ejemplo n.º 5
0
def search():
    form = SearchForm(request.args)
    books = BookCollection()

    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        book = Book.query.filter_by(title=q).all()
        if book:
            books = book
            key = q
            num = len(book)

        else:
            isbn_or_key = is_isbn_or_key(q)
            share_book = ShareBooks()

            if isbn_or_key == 'isbn':
                share_book.search_by_isbn(q)
            else:
                share_book.search_by_keyword(q, page)

            books.fill(share_book, q)
            key = books.keyword
            num = books.total
            Book.insert_into_sql(books.books)
            books = books.books

    else:
        flash("搜索的关键字不符合要求,请重新输入关键字")
    return render_template('search_result.html',
                           keyword=key,
                           total=num,
                           books=books)
Ejemplo n.º 6
0
def search():
    form = BookSearchForm().validate_for_api()
    q = form.q.data
    if is_isbn_or_key(q) == 'key':
        books = Book.search_by_keywords(q)
    else:
        books = [Book.get_book_by_isbn(q)]
    return jsonify(books), 200
Ejemplo n.º 7
0
def add_book():
    form = BookForm(request.form)
    if request.method == 'POST' and form.validate():
        with db.auto_commit(throw=False):
            book = Book()
            book.set_attrs(form.data)
            db.session.add(book)
    return render_template('book/add_book.html', form=form)
Ejemplo n.º 8
0
    def persistence_book(cls, book):
        book_model = Book()
        book_model.set_attr(book['data'])

        # book_model.isbn = get_isbn(book['data'])
        # book_model.image = book['images']['large']
        db.session.add(book_model)
        db.session.commit()
        return book_model
Ejemplo n.º 9
0
def two_saved_books(app):
    # Arrange
    ocean_book = Book(title="Ocean Book", description="watr 4evr")
    mountain_book = Book(title="Mountain Book", description="i luv 2 climb rocks")

    db.session.add_all([ocean_book, mountain_book])
    # Alternatively, we could do
    # db.session.add(ocean_book)
    # db.session.add(mountain_book)
    db.session.commit()
Ejemplo n.º 10
0
def set_data():
    print('开始生成虚拟数据......')
    try:
        User.generate_fake(50)
        Book.generate_fake(50)
        Present.generate_fake(50)
        Wish.generate_fake(50)
    except Exception as e:
        raise e
    print('完成....')
Ejemplo n.º 11
0
def two_saved_books(app):
    #Arrange
    ocean_book = Book(title="Ocean Book", description="water forever")
    mountain_book = Book(title="Mountain Book",
                         description="I love to climb mountains")
    db.session.add_all([ocean_book, mountain_book])
    #Alternatively, we could do
    #db.session.add(ocean_book)
    #db.session.add(mountain_book)
    db.session.commit()
Ejemplo n.º 12
0
def add_book(title, author, genre, read):
    book = Book(
        title=title,
        author=author,
        genre=genre,
        read=read
    )
    db.session.add(book)
    db.session.commit()

    return book.to_dict()
Ejemplo n.º 13
0
def two_saved_books(app):
    # This fixture needs to request the use of the app fixture, defined previously, so we know the test database has been initialized.
    # Arrange
    ocean_book = Book(title="Ocean Book", description="watr 4evr")
    mountain_book = Book(title="Mountain Book",
                         description="i luv 2 climb rocks")

    db.session.add_all([ocean_book, mountain_book])
    # Alternatively, we could do
    # db.session.add(ocean_book)
    # db.session.add(mountain_book)
    db.session.commit()
Ejemplo n.º 14
0
    def search_by_isbn(self, isbn):
        isbn_url = self.isbn_url.format(isbn)
        result = Http.get(isbn_url)

        # 从数据库查询是否有该书,如果没有,执行保存数据库,有的话跳过
        book = Book()
        res = Book.query.filter_by(isbn=result['isbn']).first()
        if res is None:
            book.set_attrs(result)
            db.session.add(book)
            db.session.commit()

        self.__fill_single(result)
Ejemplo n.º 15
0
def create_book():
    """
	POST /books
	:return: Book created
	"""
    req_data = request.get_json()  # turn json into Python objects

    try:
        isbn_str = str(req_data['isbn'])

        if (req_data['title'] == "") or (
                req_data['title'].isspace()):  # check title is not empty
            return jsonify({"message": "Title can't be empty"}), 400

        if (req_data['isbn'] == "") or (
                req_data['isbn'].isspace()):  # check title is not empty
            return jsonify({"message": "isbn can't be empty"}), 400

        if (len(isbn_str) < 10) or (len(isbn_str) >
                                    15):  # confirm length of isbn is 10 - 15
            return jsonify(
                {"message": "isbn number must be between 10 - 15 characters"})

        if isinstance(req_data['author'],
                      (list, str)) and (req_data['author'] != ""
                                        or req_data['author'].isspace()
                                        ):  # confirm author is a list type
            print(req_data['author'])
            for book in books_collection:
                if book["isbn"] == req_data[
                        "isbn"]:  # check if book with the same ID number exists
                    return jsonify({"message": 'Book already exists'
                                    }), 400  # return this if book exists

            book = Book(req_data['title'], req_data["isbn"])  # create book

            book.set_author(req_data['author'])  # create author list

            books_collection.append(
                book.serialize())  # add book to dummy book list

            return make_response(jsonify({"message": "Book has been created"}),
                                 201)
    except KeyError:
        return jsonify(
            {"message":
             "Couldn't understand your message, please try again"}), 400

    else:
        return jsonify({"message": "Author must be a list and can't be empty"})
Ejemplo n.º 16
0
def init_book():
    books = [
        Book(title='java',
             author='李刚',
             price=20,
             isbn='35986547845',
             summery='概况'),
        Book(title='python',
             author='join',
             price=20,
             isbn='35983547845',
             summery='概况'),
    ]
    with db.auto_commit():
        db.session.add_all(books)
Ejemplo n.º 17
0
def addBook():
    """"""
    response_result = ResponseResult()
    book_collection_name = request.args.get("currentBookCollectionName")
    book_content = request.args.get("bookContent")

    book_collection = BookCollection().query.filter_by(name=book_collection_name).first()
    book_collection_id = book_collection.id

    book = Book()
    book.book_collection_id = book_collection_id
    book.content = book_content
    db.session.add(book)
    db.session.commit()

    return json.dumps(response_result, default=lambda o: o.__dict__)
Ejemplo n.º 18
0
async def read_books_by_author(author: List[str] = Query(...)):
    all_books = []

    for name in author:
        url = GOOGLE_BOOKS
        author_string = name.split()

        if len(author_string) > 1:
            author_string = "+".join(author_string)
            author_string = f'"{author_string}"'
        else:
            author_string = author_string[0]

        url += f"?q=inauthor:{author_string}&fields=items/volumeInfo"

        async with httpx.AsyncClient() as client:
            response = await client.get(url)
            response.raise_for_status()
            data = response.json()

        books_list = data.get("items", {})
        books_list = [book.get("volumeInfo", {}) for book in books_list]
        parsed_books = list(map(get_book_fields, books_list))
        all_books.extend(parsed_books)

    return [Book(**book) for book in all_books]
Ejemplo n.º 19
0
async def read_books(q: str = "Hobbit",
                     published_date: Optional[str] = None,
                     sort_by_date: Optional[bool] = False,
                     newest_first: Optional[bool] = False):
    url = GOOGLE_BOOKS + f"?q={q}&fields=items/volumeInfo"

    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        response.raise_for_status()
        data = response.json()

    books_list = data.get("items", {})
    books_list = [book.get("volumeInfo", {}) for book in books_list]
    parsed_books = list(map(get_book_fields, books_list))

    if published_date:
        parsed_books = [
            book for book in parsed_books
            if published_date in book["published_date"]
        ]

    if sort_by_date:
        parsed_books.sort(key=lambda b: books_sort(b["published_date"]))
        if newest_first:
            parsed_books = parsed_books[::-1]

    return [Book(**book) for book in parsed_books]
Ejemplo n.º 20
0
def handle_books():
    if request.method == "GET":
        #gets query param called title from the request, returns value of query param
        title_query = request.args.get("title")
        if title_query:
            books = Book.query.filter_by(
                title=title_query
            )  #if we get query param, will filter the results
        else:  #if we didnt get a query param, get all the books
            books = Book.query.all()  #tells Book to query for all books
        books_response = []
        for book in books:  #iterate over all books in books to collect their data and format it into a response
            books_response.append({
                "id": book.id,
                "title": book.title,
                "description": book.description
            })  #creates a list of dictionaries
        return jsonify(books_response
                       )  #jsonfy turns books response into a response object
    elif request.method == "POST":
        #request body holds the body contents of the HTTP request in json form
        request_body = request.get_json()
        #print(request_body)
        #create an instance of Book using the data from request_body
        new_book = Book(title=request_body["title"],
                        description=request_body["description"])

        db.session.add(new_book)
        db.session.commit()

        return make_response(f"Book {new_book.title} successfully created",
                             201)
Ejemplo n.º 21
0
def handle_books():
    if request.method == "GET":
        if request.method == "GET":
            title_query = request.args.get("title")
        if title_query:
            books = Book.query.filter_by(title=title_query)
        else:
            books = Book.query.all()

        books_response = []
        for book in books:
            books_response.append({
                "id": book.id,
                "title": book.title,
                "description": book.description
            })
        return jsonify(books_response)

    elif request.method == "POST":
        request_body = request.get_json()
        new_book = Book(title=request_body["title"],
                        description=request_body["description"])

        db.session.add(new_book)
        db.session.commit()

        return make_response(f"Book {new_book.title} successfully created",
                             201)
Ejemplo n.º 22
0
def handle_books(
):  # this function will execute whenever a request that matches the decaorator is received
    if request.method == "GET":

        # each Model class has a query attribute; the object returned by this attribute has the functions we will use to retrieve model data from the database
        books = Book.query.all(
        )  # tells Book to query for all() books. This method returns a list of instances of Book.
        books_response = []
        for book in books:
            books_response.append({
                "id": book.id,
                "title": book.title,
                "description": book.description
            })

        return jsonify(books_response)

    elif request.method == "POST":
        request_body = request.get_json(
        )  # we use the request object to get information about the HTTP request; this method "Pythonifies" the JSON HTTP request body by convertign it to a Python dictionary

        #create new instance of Book model
        new_book = Book(title=request_body["title"],
                        description=request_body["description"])

        # adds new instance to the database (staging)
        db.session.add(new_book)
        # commits the changes, make it happen (action itself)
        db.session.commit()

        return make_response(f"Book {new_book.title} has been created",
                             201)  # instantiates a Response object
Ejemplo n.º 23
0
 def create_book_model(json):
     model = Book(title=json['title'],
                  author=json['author'],
                  isbn=json['isbn'],
                  price=json['price'],
                  publisher=json['publisher'],
                  image=json['image'])
     return model
Ejemplo n.º 24
0
def create_book():
    request_body = request.get_json()
    new_book = Book(title=request_body["title"],
                    description=request_body["description"])

    db.session.add(new_book)
    db.session.commit()

    return make_response(f"Book {new_book.title} successfully created")
Ejemplo n.º 25
0
def handle_books():
    request_body = request.get_json()
    new_book = Book(title=request_body['title'],
                        description=request_body['description'])
    db.session.add(new_book)
    db.session.commit()
    return {
        "success": True,
        "message": f'Book {new_book.title} has been created!!'
    }, 201
Ejemplo n.º 26
0
 def post():
     data = request.form
     book = Book(name=data['name'], summary=data['summary'])
     db.session.add(book)
     db.session.commit()
     for authors in data['author']:
         if authors is not '':
             details = Book.query.order_by(Book.id.desc()).first()
             db.session.add(
                 AuthorBook(author_id=authors, book_id=details.id))
             db.session.commit()
Ejemplo n.º 27
0
def search():
    form = BookSummaryForm().validate_for_api()
    start, count = offset_limit()
    q = request.args.get('q', None)
    books = Book.get_paginate_models(start, count, q, err_msg='相关书籍不存在')
    # 搜索关键字次数加1
    Keyword.add(q)
    if form.summary.data == '1':
        for book in books['models']:
            book._fields = ['author', 'id', 'image', 'isbn', 'price', 'title']
    return jsonify(books)
Ejemplo n.º 28
0
def add_book():
    request_body = request.get_json()
    new_book = Book(title = request_body["title"],
                    description = request_body["description"])
        
    db.session.add(new_book)
    db.session.commit()

    return {
        "success": True,
        "message": f"Book {new_book.title} has been created."
    }, 201
Ejemplo n.º 29
0
async def read_book(book_id: str):
    url = GOOGLE_BOOKS + f"/{book_id}?fields=volumeInfo"
    async with httpx.AsyncClient() as client:
        response = await client.get(url)
        response.raise_for_status()
        data = response.json()

    current_book = data.get("volumeInfo", {})

    parsed_book = get_book_fields(current_book)

    return Book(**parsed_book)
Ejemplo n.º 30
0
def submitBook():
    """"""
    response_result = ResponseResult()
    book_id = request.args.get("editBookId")
    book_content = request.args.get("editContent")
    print(book_id)
    print(book_content)
    if (book_id != "-1"):
        try:
            edit_book = Book().query.filter_by(id=book_id).first()
            edit_book.content = book_content
            db.session.commit()
            response_result.message = "提交成功"
        except Exception as e:
            print(e)
            response_result.ret = "fail"
            response_result.message = "提交失败"
    else:
        response_result.ret = "fail"
        response_result.message = "还没有选中笔记呢!"
    return json.dumps(response_result, default=lambda o: o.__dict__)