Example #1
0
 def get(self,uid):
     user_model = UserModel()
     book_model = BookModel()
     info = user_model.get_user(uid)
     current = book_model.get_current(uid)
     data = {}
     current_list = []
     for book in current:
       item = {}
       item["rent_time"] = book[0].date()
       item["return_time"] = book[1].date()
       item["title"] = book[2]
       item["images"] = book[3]
       item["author"] = book[4]
       item["isbn"] = book[5]
       item["address"] = book[6]
       current_list.append(item)
     data["current"] = current_list
     uinfo = {}
     for user in info:
       uinfo["name"] = user[0]
       uinfo["gravator"] = user[1]
       uinfo["major"] = user[2]
       uinfo["degree"] = user[3]
       uinfo["num"] = user[4]
       uinfo["id"] = user[5]
     data["uinfo"] = uinfo
     self.render("user.html",data=data)
Example #2
0
    def post(self):
        posted_data = request.get_json()

        if get_jwt_identity()["access level"] <= 1:
            return {
                "message": "only admins",
                "user": get_jwt_identity(),
                "status code": 401
            }

        if BookModel.validate_book(**posted_data["book"]):
            return BookModel.validate_book(**posted_data["book"])

        if book_lists.count_documents({'name': posted_data["booklist name"]},
                                      limit=1) == 0:
            return {"message": "booklist doesn't exist", "status code": 404}

        book_lists.update({"name": posted_data["booklist name"]},
                          {"$push": {
                              'booklist': posted_data["book"]
                          }})

        return {
            "message": "book added succesfuly",
            "user": get_jwt_identity(),
            "status code": 200
        }
Example #3
0
 def post(self):
    number = self.get_argument("number")
    passwd = self.get_argument("passwd")
    select = self.get_argument("select")
    user = {"number": number} # user info object
    post = {
        "number": number,
        "passwd": passwd,
        "select": select
        }
    user_model = UserModel()
    user = user_model.get_info(post["number"])
    # 判断用户是否已经存在
    if not user:
      user = User(post).import_user() # import users 
      book_model = BookModel()
      if user_model.import_user(user,post["number"]):
        user = user_model.get_info(user["number"])
        # 判断用户是否已经导入数据
        if book_model.is_import(user["id"]):
          book = Book(post).get_remote_book(True)
        else:
          book = Book(post).get_remote_book(False)
        book_model.import_book(book,user["id"])
      # 将用户信息存入cookie
      self.set_current_user(user)
    self.write(json.dumps({"error_code":"200"}))
Example #4
0
 def delete(self, book_id):
     '''Remove a book by book id'''
     book = BookModel.find_by_id(book_id)
     if book:
         BookModel.delete_from_db(book)
         return {'message' : 'book with id {} has been removed.'.format(book_id)}, 200
     return {'message' : 'book with id {} is not found.'.format(book_id)}, 404
Example #5
0
    def put(self, param):
        """
        Method editing book.
        Returns a string.
        """
        item = request.get_json() if request.get_json() else request.args
        try:
            if item:
                model = BookModel()
                # case if numeric is id
                if param.isnumeric():
                    model = BookModel.get_by_id(param)
                else:
                    model = BookModel.get_by_name(param)
                if 'name' in item:
                    model.name = item['name']
                if 'edition' in item:
                    model.edition = item['edition']
                if 'publication_year' in item:
                    model.publication_year = item['publication_year']
                model.save()
                return 'Edited', 204
            else:
                return 'Unedited, invalid payload', 400
        except Exception as e:

            return f"{e}", 500
Example #6
0
 def post(self, rec_id, return_date):
     return_day = DateRead.read_date(return_date)
     try:
         loan_rec = LoanRecordModel.find_by_id(rec_id)
         book = BookModel.find_by_id(loan_rec.book_id)
     except Exception as e:
         return {'message': 'Error, cannot find this loan record'}, 400
     LoanRecordModel.complete_loan_record(loan_rec.id, return_day)
     BookModel.mark_returned(book)
     return {
         'message': 'book {} is successfully returned'.format(book.id)
     }, 200
Example #7
0
    def put(self, book_id, author, title, date, genre):
        '''Update a book by book id'''
        cur_book = BookModel.find_by_id(book_id)

        if not cur_book:
            return {'message' : 'book with id {} is not found.'.format(book_id)}, 404

        new_author = AuthorModel.search_and_add_author(author)
        new_genre = GenreModel.search_and_add_genre(genre)
        new_date = DateRead.read_date(date)

        cur_book = BookModel.update_book(book_id, title, new_author, new_date, new_genre)
        return cur_book.json(), 200
Example #8
0
    def post(self):
        # parse_args() return only arguments added by add_argument as Namespace
        # Any missing added argument will stop and return help message to the browser
        data = Book.parser.parse_args()

        # data namespace is rolled into one argument (**data)
        book = BookModel(**data)

        try:
            book.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return book.json(), 201
Example #9
0
    def post(self, title, author, date, genre):
        '''Add a new book'''
        cur_author = AuthorModel.search_and_add_author(author)

        cur_genre = GenreModel.search_and_add_genre(genre)

        release_date = DateRead.read_date(date)

        #create the new book, add into db
        new_book = BookModel(title, cur_author.id, release_date, cur_genre)
        new_book.save_to_db()

        if not new_book:
            return {"message" : "add book error"}, 403
        return new_book.json(), 201
Example #10
0
    def put(self, book_id):
        data = Book.parser.parse_args()
        book = BookModel.findById(book_id)

        if book is None:
            book = BookModel(data['book_title'], data['book_description'],
                             data['book_genre'])
        else:
            book.book_title = data['book_title']
            book.book_description = data['book_description']
            book.book_genre = data['book_genre']
            book.book_update = datetime.now()

        book.saveToDb()
        return book.json()
Example #11
0
 def post(self, book_id, user_id, loan_date, due_date):
     '''Create a new loan record'''
     loan_day = DateRead.read_date(loan_date)
     due_day = DateRead.read_date(due_date)
     try:
         book = BookModel.find_by_id(book_id)
     except Exception as e:
         return {'message': 'loan book error, book or user not found'}, 400
     if not BookModel.check_availability(book):
         return {
             'message': 'book {} has been loaned out'.format(book_id)
         }, 400
     loanrec = LoanRecordModel.create_loan_record(book_id, user_id,
                                                  loan_day, due_day)
     BookModel.mark_loaned_out(book)
     return loanrec.json(), 201
 def delete(self):
     number_of_books_deleted = BookModel.delete_all_books()
     number_of_comments_deleted = CommentModel.delete_all_comments()
     return {
         "message":
         f"{number_of_books_deleted} books and {number_of_comments_deleted} comments successfully deleted"
     }
Example #13
0
    def put(self, book_id):
        data = Book.parser.parse_args()

        book = BookModel.find_by_id(book_id)

        if book is None:  # Create a new book if it does not exist in the database
            book = BookModel(**data)
        else:  # Update the book if it exists in the database
            book.book_title = data['book_title']
            book.book_description = data['book_description']
            book.book_genre = data['book_genre']
            book.book_update = datetime.now()

        book.save_to_db()

        return book.json()
Example #14
0
 def post(self, id_account, id_book):
     acc = AccountModel.find_by_id(id_account)
     if not acc:
         return {
             'message':
             "Account with ['id': {}] not found".format(id_account)
         }, 404
     book = BookModel.find_by_id(id_book)
     if not book:
         return {
             'message': "Book with ['id': {}] not found".format(id_book)
         }, 404
     wl = WishlistModel.find_by_account(id_account)
     if book in wl.books:
         return {
             'message':
             "Book with ['id': {}] is already is this wish list".format(
                 id_book)
         }, 400
     wl.books.append(book)
     wl.save_to_db()
     return {
         'message':
         "Book with ['id': {}] added to wish list".format(id_book),
         'wl': wl.json()
     }, 200
Example #15
0
 def put(self, idd):
     data = self.__parse_request__()
     review = ReviewModel.find_by_id(idd)
     if not review:
         return {
             'message': "There is no review with ['id': {}]".format(idd)
         }, 404
     review.delete_from_db()
     user = AccountModel.find_by_id(data.get('user_id'))
     book = BookModel.find_by_id(data.get('book_id'))
     if not user or not book:
         if not user:
             return {
                 'message':
                 "There is no account with ['id': {}]".format(
                     data.get('user_id'))
             }, 404
         if not book:
             return {
                 'message':
                 "There is no book with ['id': {}]".format(
                     data.get('book_id'))
             }, 404
     new_review = ReviewModel(data.get('title'), data.get('user_id'),
                              data.get('book_id'), data.get('date'),
                              data.get('valuation'), data.get('comment'))
     new_review.save_to_db()
     user.reviews.append(new_review)
     book.reviews.append(new_review)
     return new_review.json(), 200
Example #16
0
    def get(self, start_date, end_date):
        '''Get books by start date and end date'''
        start = DateRead.read_date(start_date)
        end = DateRead.read_date(end_date)

        books = BookModel.find_by_date_range(start, end)
        book_list = [book.json() for book in books]
        return book_list, 200
Example #17
0
 def get(self, title):
     '''Search a book by book title'''
     try:
         books = BookModel.find_by_name(title)
     except Exception as e:
         return [], 404
     book_list = [book.json() for book in books]
     return book_list, 200
Example #18
0
 def get(self, book_id):
     '''Get the loan record'''
     try:
         book = BookModel.find_by_id(book_id)
     except Exception as e:
         return {'message': 'book {} not found'.format(book_id)}, 404
     loan_records = LoanRecordModel.find_by_book_id(book_id)
     return [loan_rec.json() for loan_rec in loan_records], 200
Example #19
0
 def delete(self, isbn):
     try:
         book = BookModel.find_by_isbn(isbn)
         if book:
             book.delete_from_db()
     except:
         return {'message': 'An error occured deleting the book.'}, 500
     return {'message': 'Book deleted'}
Example #20
0
 def put(self, isbn):
     data = Book.parser.parse_args()
     book = BookModel.find_by_isbn(isbn)
     if book is None:
         book = BookModel(isbn, **data)
     else:
         book.title = data['title']
         book.authors = data['authors']
         book.description = data['description']
         book.cover = data['cover']
     try:
         book.save_to_db()
     except:
         return {
             'message': 'An error occured creating/updationg the book.'
         }, 500
     return book.json()
Example #21
0
 def get(self, isbn):
     try:
         book = BookModel.find_by_isbn(isbn)
     except:
         return {'message': 'An error occured searching the book.'}, 500
     if book:
         return book.json()
     return {'message': 'Book not found'}, 404
Example #22
0
 def post(self):
     args = self.reqparse.parse_args()
     book = BookModel(args.title, args.author, args.item_caption,
                      args.image_url, args.item_url, args.image)
     db.session.add(book)
     db.session.commit()
     res = BookSchema().dump(book).data
     return res, 201
Example #23
0
 def delete(cls, book_id):
     book = BookModel.find_by_id(book_id)
     if not book:
         return {"message": "Book not found"}, 404
     if book.is_borrowed:
         return {"message": "Borrowed book can\'t be deleted"}, 400
     book.delete_from_db()
     return {"message":"Book deleted"}, 200
 def delete(self, book_id):
     book = BookModel.find_by_id(book_id)
     number_of_comments_deleted = CommentModel.delete_all_from_book(book_id)
     book.delete_from_db()
     return {
         "message":
         f"1 book ands {number_of_comments_deleted} comments deleted successfully."
     }
Example #25
0
 def put(self, idd):
     data = self.__parse_request__()
     exists = BookModel.find_by_id(idd)
     if not exists:
         return {
             'message': "A book with ['id': {}] not found".format(idd)
         }, 404
     authors = []
     exists.author = []
     exists.save_to_db()
     a = AuthorModel.find_by_name(data.get('author_name'))
     if a:
         authors.append(a)
     else:
         new_author = AuthorModel(data.get('author_name'),
                                  data.get('author_bd'),
                                  data.get('author_city'),
                                  data.get('author_country'))
         authors.append(new_author)
         new_author.save_to_db()
     exists.delete_from_db()
     new_book = BookModel(data.get('isbn'), data.get('name'), authors,
                          data.get('genre'), data.get('year'),
                          data.get('editorial'), data.get('language'),
                          data.get('price'), data.get('synopsis'),
                          data.get('description'), data.get('num_pages'),
                          data.get('cover_type'), data.get('num_sales'),
                          data.get('total_available'),
                          data.get('cover_image_url'),
                          data.get('back_cover_image_url'))
     new_book.id = idd
     new_book.save_to_db()
     return new_book.json(), 200
Example #26
0
    def put(self, id):
        book_data = BookModel.find_by_id(id)
        book_json = request.get_json()

        book_data.title = book_json['title']
        book_data.status = book_json['status']

        book_data.save_to_db()
        return book_schema.dump(book_data), 200
Example #27
0
 def json(self):
     book = BookModel.find_by_id(self.book_id)
     return {
         "id": self.id,
         "price": self.price,
         "categoria": self.categoria,
         "quant": self.quant,
         "book_title": book.name
     }
    def get_already_opened_books(self) -> dict:
        books = {}
        for row in self.connection.cursor().execute(self.__get_base_query()):
            book_id = row[self._col_id]
            title = row[self._col_title]
            author = row[self._col_author]
            books[book_id] = BookModel(title, author)

        return books
Example #29
0
 def get(self, genre=None):
     if genre:
         return {
             'books':
             [i.json()['book'] for i in BookModel.find_by_genre(genre)]
         }, 200
     return {
         'books':
         [i.json()['book'] for i in db.session.query(BookModel).all()]
     }, 200
Example #30
0
 def get(self,uid):
   result = {}
   book_model = BookModel()
   user_info = self.get_current_user()
   current = book_model.get_current(uid)
   result = {"user":user_info}
   book_list = []
   for book in current:
     item = {}
     item["rent_time"] = book[0].date()
     item["return_time"] = book[1].date()
     item["title"] = book[2]
     item["images"] = book[3]
     item["author"] = book[4]
     item["isbn"] = book[5]
     item["address"] = book[6]
     book_list.append(item)
   result["book"] = book_list
   self.render("current.html",data=result)
Example #31
0
 def get(self, book_id):
     book = BookModel.find_by_id(book_id)
     if not book:
         return {
             'message': "Book with ['id': {}] not found".format(book_id)
         }, 404
     return {
         'reviews':
         [i.json()['review'] for i in ReviewModel.find_by_book(book_id)]
     }, 200
Example #32
0
 def delete(self, param):
     """
     Method that removes book.
     Returns a string.
     """
     try:
         # case if numeric is id
         if param.isnumeric():
             book = BookModel.get_by_id(param)
             authors = AuthorBookModel.filter_by_book_id(param)
         else:
             book = BookModel.get_by_name(param)
             authors = AuthorBookModel.filter_by_book_id(book.id)
         book.delete()
         for author_association in authors:
             author_association.delete()
         return 'No Content', 204
     except Exception as e:
         return f"{e}", 500
 def create_loan_record(cls, book_id, user_id, loan_date, due_date):
     book = BookModel.find_by_id(book_id)
     if not book:
         raise BookNotFoundException("no book match this id")
     user = UserModel.find_by_id(user_id)
     if not user:
         raise UserNotFoundException("no user match this id")
     new_record = LoanRecordModel(book_id, user_id, loan_date, due_date)
     new_record.save_to_db()
     return new_record
Example #34
0
 def get(self,page=1):
     book_model = BookModel()
     books = book_model.get_time_line(int(page))
     book_list = []
     data = {}
     for book in books["info"]:
       item = {}
       item["title"] = book[0]
       item["rent_time"] = book[1].date()
       item["return_time"] = book[2].date()
       item["name"] = book[3]
       item["images"] = book[4]
       item["author"] = book[5]
       item["isbn"] = book[6]
       item["uid"] = book[7]
       book_list.append(item)
     for num in books["num"]:
       data["num"] = int(math.ceil(num[0]/10))
     data["book"] = book_list
     data["current"] = int(page)
     self.render("index.html",data=data)
Example #35
0
	def create(self):
		
		# Get all params from the html form
		data = self.get_data("title",
		                     "blob",
		                     "author",
		                     "genre",
		                     "description",
		                     "author_description")
		
		fields = [data["title"], data["author"], data["genre"],
				  data["description"], data["author_description"]]
		
		invalid_form = BookModel.invalid_form(fields, data["blob"])
		
		if not invalid_form:
			for f in fields:
				f = utils.escape(f) # HTML-Safe
			return data
		else:
			self.redirect('/books/new')