[英]can't return json pagination in flask for REST API
我正在使用Miguel Grinberg的Flask REST API repo,但我沒有返回JSON分頁結果。 這些示例在線使用html模板,但我只想返回一些結果(20),並最終返回上一頁和下一頁的鏈接。 當我在這句話之后立即返回代碼時,我得到“分頁對象不可迭代”:
def get_customers():
return jsonify({'customers': [customer.get_url() for customer in
Customer.query.paginate(page=1, per_page=1)]})
我知道我傳遞了錯誤的對象,但我不確定是否應該使用另一個模塊,或者我是否在正確的道路上。 有沒有人有建議達到我的最終目標?
Miguel的回購中的原始代碼是:
@app.route('/customers/', methods=['GET'])
def get_customers():
return jsonify({'customers': [customer.get_url() for customer in
Customer.query.all()]})
整個文件在這里: https : //github.com/miguelgrinberg/oreilly-flask-apis-video/blob/a460ad9df2e58c13b90f183e81b4e8953eb186cb/orders/api.py
我正在使用的相關代碼:
class Customer(db.Model):
__tablename__ = 'customers'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), index=True)
def get_url(self):
return url_for('get_customer', id=self.id, _external=True)
def export_data(self):
return {
'self_url': self.get_url(),
'name': self.name
}
def import_data(self, data):
try:
self.name = data['name']
except KeyError as e:
raise ValidationError('Invalid customer: missing ' + e.args[0])
return self
@app.route('/customers/', methods=['GET'])
def get_customers():
return jsonify({'customers': [customer.get_url() for customer in
Customer.query.paginate(page=1, per_page=1)]})
@app.route('/customers/<int:id>', methods=['GET'])
def get_customer(id):
return jsonify(Customer.query.get_or_404(id).export_data())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.