示例#1
0
    def post(self, item_id):
        ret = BooksModel.find_by_id(item_id)

        if ret is not None:
            return {"message": f"ID {item_id} უკვე არსებობს სიაში"}, 400

        book = Item.i_prs.parse_args()
        bm = BooksModel(**book)
        bm.save()
        return {"message": f"book {item_id} is added successfully"}, 200
示例#2
0
def rate_movies(token):
    try:
        user_id, book_data = Users.decode_token(token), request.get_json()
        for book in book_data:
            bookAttributeList = []
            for attribute, value in book.items:
                bookAttributeList.append(value)
            newRatings = Books(user_id, bookAttributeList[0],
                               bookAttributeList[1])
            newRatings.add_rating()
            # initialiseBookModel()
        return jsonify({'books': book_data, 'message': 'Ratings added'}), 201
    except Exception as ex:
        return jsonify({'Error': ex, 'message': 'Add Ratings failed'}), 400
示例#3
0
 def put(self, item_id):
     book = Item.i_prs.parse_args()
     book_from_db = BooksModel.find_by_id(item_id)
     print(book_from_db)
     if book_from_db is not None:
         # update
         book_from_db.name = book.name
         book_from_db.author = book.author
         book_from_db.genre = book.genre
         book_from_db.publishdate = book.publishdate
         book_from_db.quantity = book.quantity
         book_from_db.save()
         return {"message": f"book {item_id} is updated successfully"}, 200
     # insert
     book = Item.i_prs.parse_args()
     bm = BooksModel(**book)
     bm.save()
     return {"message": f"book {item_id} is added successfully"}, 200
示例#4
0
def bookdetails(book_isbn):
    revs = list()

    # when the user is leaving a review about that specific book
    if request.method == 'POST':
        row = db.execute("select id from books where isbn = :isbn ", {
            'isbn': book_isbn
        }).fetchone()
        book_id = row[0]
        rating = request.form['rate']
        review = request.form['review']

        # if the user entered an empty input he will be directed to the error page
        if rating == None or not review.strip():
            return render_template(
                'error.html',
                error="you must provide both rate and review !",
                direction="/bookpage")

        # after validating the user input, it will be stored into the database and displayed
        else:
            try:
                db.execute(
                    'insert into reviews(bookid,userid,review,rating) VALUES(:book_id,:user_id,:review,:rating)',
                    {
                        'book_id': book_id,
                        'user_id': session['user_id'],
                        'review': review,
                        'rating': rating
                    })
                db.commit()
                return redirect(request.referrer)
            # expecting that the user would make a review more than once about the same book
            except:
                return render_template(
                    "error.html",
                    error="you already made a review on this book",
                    direction="/bookpage")

    # when the user is just requesting for the bookdetails page , the book info and it`s reviews will be displayed for him
    else:
        try:
            book = db.execute("select * from books where isbn = :isbn", {
                'isbn': book_isbn
            }).fetchone()
        except:
            return render_template("error.html",
                                   error="error fetching data",
                                   direction="/bookpage")
        oneBook = Books(int(book['id']), book['author'], book['title'],
                        book_isbn, book['year'])

        # getting any review about that book
        try:
            reviews = db.execute(
                'Select rating, review, userid from reviews where bookid = :bookid',
                {
                    'bookid': book.id
                }).fetchall()
        except:
            return render_template("error.html",
                                   error="error fetching data",
                                   direction="/bookpage")

        # parsing data to a list of UserReview instance
        for i in range(len(reviews)):
            # parsing the users who made the reviews
            user = db.execute('select username from users where id = :userid',
                              {
                                  'userid': reviews[i]['userid']
                              }).fetchone()
            oneReview = UserReview(reviews[i]['review'], user['username'],
                                   reviews[i]['rating'])
            revs.append(oneReview)

        ## calling the function to get the data from goodreads api
        greview = get_reviews(book_isbn)
        return render_template("bookdetails.html",
                               book=book,
                               greview=greview,
                               reviews=revs)
示例#5
0
def create_app():
    app = Flask(__name__)
    app.config["JWT_SECRET_KEY"] = os.getenv("SECRET_KEY")
    app.config["JWT_BLACKLIST_ENABLED"] = True
    app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = ['access']
    app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0
    jwt = JWTManager(app)

    # Check for environment variable
    if not os.getenv("DATABASE_URL"):
        raise RuntimeError("DATABASE_URL is not set")

    # Configure session to use filesystem
    app.config["SESSION_PERMANENT"] = False
    app.config["SESSION_TYPE"] = "filesystem"
    Session(app)

    # Storage engine to save revoked token
    blacklist = set()

    # check if token exist in blacklist
    @jwt.token_in_blacklist_loader
    def check_if_token_in_blacklist(decrypted_token):
        jti = decrypted_token['jti']
        return jti in blacklist

    # Set up assets
    # setup_assets(app)

    # Set up database
    engine = create_engine(os.getenv("DATABASE_URL"))
    db = scoped_session(sessionmaker(bind=engine))

    # get API key
    API_KEY = os.getenv("API_KEY")
    API_URL = "https://www.goodreads.com/book/review_counts.json"

    # User authentication class instance
    auth = Auth()

    # models
    books = Books(db)
    reviews = Reviews(db)

    # Home route (book list)
    @app.route("/")
    @login_required
    def index():
        return render_template('index.html')

    # Book list page
    @app.route("/library")
    @login_required
    def library():
        return render_template(
            'library.html',
            data={
                "result": books.fetchall(query="ORDER BY id LIMIT 50"),
                "row_count": books.count()
            })

    # search endpoint
    @app.route("/book/search")
    @login_required
    def search():
        return jsonify({"result": books.search(request.args.get('q'))}), 200

    @app.route("/book/<int:book_id>")
    @login_required
    def show_book(book_id):
        book = books.fetchone(query="where books.id = :id",
                              value={"id": book_id})
        api_res = api_fetch.get(API_URL,
                                params={
                                    "key": API_KEY,
                                    "isbns": book['isbn']
                                })
        formatted_data = format_reviews_data(api_res) if api_res else {}

        return render_template(
            'book.html',
            book=book,
            reviews=reviews.fetchall(
                query="where book_id = :book_id  ORDER BY id DESC",
                value={"book_id": book['id']}),
            good_read_data=formatted_data)

    # store review
    @app.route("/book/<int:book_id>", methods=["POST"])
    @login_required
    def store_review(book_id):
        validated = validate_reviews(reviews, book_id, request, session)
        if validated is True:
            review = reviews.insert({
                "user_id": session['user_id'],
                "book_id": book_id,
                "comment": request.json.get('comment'),
                "rating": request.json.get('rating')
            })
            return jsonify({"result": review}), 200
        else:
            return validated, 500

    # return data for pagination
    @app.route("/books")
    @login_required
    def books_as_json():
        return books.paginate(request), 200

    # API Access
    @app.route('/api/<string:isbn>')
    def get_reviews(isbn):
        return jsonify(books.join_reviews(isbn)), 200

    @app.route("/logout", methods=['GET'])
    @login_required
    def logout():
        session['access_token'] = None
        return redirect(url_for('login'))

    @app.route("/login", methods=["GET", "POST"])
    @is_login
    def login():
        if request.method == "GET":
            return render_template('auth/login.html')
        if request.method == "POST":
            email = request.json.get('email', None)
            password = request.json.get('password', None)
            token = auth.authenticate(db, email=email, password=password)
            return jsonify(token), 200 if not token['error'] else 404

    @app.route("/signup", methods=["GET", "POST"])
    @is_login
    def signup():
        if request.method == "GET":
            return render_template('auth/signup.html')
        elif request.method == "POST":
            new_user = request.get_json()
            result = auth.create_user(db, new_user)

            return jsonify(result), 200 if not result['error'] else 500

    # to be update for full working, does not involve in current registration process
    @app.route("/reset-password", methods=["GET", "POST"])
    def reset_password():
        if request.method == "GET":
            return render_template('auth/reset-password.html')

    @app.route("/email-verification", methods=["GET", "POST"])
    def verify_email():
        if request.method == "GET":
            return render_template('auth/email-verification.html')

    @app.route("/update-db")
    def update_db():
        result = db.execute('SELECT * FROM books').fetchall()
        return jsonify([dict(row) for row in result])

    return app
示例#6
0
def deletebyid(id):
    try:
        response.status = Books.deleteById(id)
    except:
        response.status = 400
示例#7
0
def uptdAvailability(id):
    try:
        data = request.body.readlines()[0]
        response.status = Books.UpdateAvailability(id, data)
    except:
        response.status = 400
示例#8
0
def createBook():
    try:
        data = request.body.readlines()[0]
        response.status = Books.createBook(data)
    except:
        response.status = 400
示例#9
0
def book(id):
    return Books.getAllOfAuthor(id)
示例#10
0
def book(id):
    return Books.getById(id)
示例#11
0
def bookslist():
    return Books.getAll()
示例#12
0
 def delete(self, item_id):
     ret = BooksModel.find_by_id(item_id)
     if ret is not None:
         BooksModel.delete(item_id)
         return {"message": "book is deleted successfully"}, 200
     return {"message": "book is not deleted"}, 400
示例#13
0
 def get(self, item_id=None):
     ret = BooksModel.find_by_id(item_id)
     if ret is not None:
         return jsonify(ret.json())
     return {"message": f"Item with ID {item_id} was not found"}, 200