我如何将分页作为jsonify()返回前端

时间:2020-08-28 04:43:01

标签: python flask flask-restful

这是我的管理图书清单,我想向其中添加分页。如何添加分页并以jsonify()的形式返回到vue作为前端?

@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)

感谢您的提前帮助!

1 个答案:

答案 0 :(得分:0)

我得到了答案,这就是我在jsonify()中返回Flask Restful Api分页的原因。MiguelGrinberg的Flask Book帮助我理解了这个概念

@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

我希望这会对以后以与我相同的方式做事的人有所帮助