简体   繁体   中英

can't return json pagination in flask for REST API

I'm working with Miguel Grinberg's Flask REST API repo, and I'm failing to return JSON paginated results. The examples online use html templates, but I just want to return a number of results (20), and eventually return links for the previous and next pages. When I return the code immediately following this sentence, I get "pagination object is not iterable":

def get_customers():
    return jsonify({'customers': [customer.get_url() for customer in
                                  Customer.query.paginate(page=1, per_page=1)]})

I understand I'm passing the wrong object, but I'm not sure if I should use another module, or if I'm on the right path. Does anyone have a suggestion to reach my end goal?

The original code in Miguel's repo is:

@app.route('/customers/', methods=['GET'])
def get_customers():
    return jsonify({'customers': [customer.get_url() for customer in
                                  Customer.query.all()]})

The whole file is here: https://github.com/miguelgrinberg/oreilly-flask-apis-video/blob/a460ad9df2e58c13b90f183e81b4e8953eb186cb/orders/api.py

The relevant code I'm working with:

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

See the API docs .

If you want to iterate over a Pagination object, use (for example)

 Customer.query.paginate(page=1, per_page=1).items

which is a collection of the items for that page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM