How Can I return pagination as jsonify() to frontend

377 views Asked by At

This is my admin book lists and I want to add pagination to it. How can I add pagination and return in jsonify() to vue as frontend?

@phonebook.route('/admin/book/list')
@admin_authorize
def admin_books(user): 
    respone_body = dict()
    respone_body['status'] = "success"
    respone_body['code'] = 0
    admin_book = admin_book(user.id, sort_by_id_desc=True)
    respone_body['data']={
        'books': admin_book,
    }
    return jsonify(respone_body)


def admin_book(user_id, sort_by_id_desc=True):
    admin_books = []
    for book in Book.query.all():
        admin_books.append({
            "id": book.id,
            "name": book.name,
            "date": book.date,
        })

    return sorted(admin_books, key=lambda dict: dict['id'], reverse=sort_by_id_desc)

Thanks for helping in advance!

1

There are 1 answers

0
Jezpython On

I got the answer, and this is how I return the Flask Restful Api pagination in jsonify().Miguel Grinberg's Flask Book helped me to understand the concept

@phonebook.route('/admin/book/list')
@admin_authorize
   def admin_books(user): 
   respone_body = dict()
   respone_body['status'] = "success"
   respone_body['code'] = 0
   admin_book, pagination = admin_book(user.id, sort_by_id_desc=True)
   respone_body['data']={
       'books': admin_book,
       'page': pagination.page,
       'per_page': pagination.per_page,
       'total_page': pagination.pages,
   }
   return jsonify(respone_body)


def admin_book(user_id, sort_by_id_desc=True):
   admin_books = [] 
   page = request.args.get('page',1,type=int) 
   per_page = current_app.config['PER_PAGE']
   pagination = Book.query.paginate(page, per_page)
   books = pagination.items
   for book in books:
       admin_books.append({
           "id": book.id,
           "name": book.name,
           "date": book.date,
    })

   return sorted(admin_books, key=lambda dict: dict['id'], reverse=sort_by_id_desc), pagination

I hope this will help someone later who do the same way I did