Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have problem with pagination. If i try this with just a list of dict it works ok, problem starts when i try use model from my DB.I have about 10k users in my sql alchemy database. User is dbModel:

class UserModel(db.Model):

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)

    username = db.Column(db.String(120), unique=True, nullable=False)

    password = db.Column(db.String(120), nullable=False)

I want to show users from 1 to 100, from 100 to 200 etc. I'm trying to use this tutorial : https://aviaryan.com/blog/gsoc/paginated-apis-flask

Here is classmethod to return model into dict:

@classmethod

def return_all(cls):

    def to_json(x):

        return {

            'id': x.id,

            'username': x.username,

            'password': x.password

        }

    return {'users': list(map(lambda x: to_json(x), UserModel.query.all()))}

Here is the pagination def:

def get_paginated_list(klass, url, start, limit):

    start = int(start)

    limit = int(limit)

    # check if page exists

    results = klass.return_all()

    count = (len(results))

    if count < start or limit < 0:

        abort(404)

    # make response

    obj = {}

    obj['start'] = start

    obj['limit'] = limit

    obj['count'] = count

    # make URLs

    # make previous url

    if start == 1:

        obj['previous'] = ''

    else:

        start_copy = max(1, start - limit)

        limit_copy = start - 1

        obj['previous'] = url + '?start=%d&limit=%d' % (start_copy,        limit_copy)

    # make next url

    if start + limit > count:

        obj['next'] = ''

    else:

        start_copy = start + limit

        obj['next'] = url + '?start=%d&limit=%d' % (start_copy, limit)

    # finally extract result according to bounds

    obj['results'] = results[(start - 1):(start - 1 + limit)]

    return obj

My api resource code is:

class AllUsers(Resource):

    def get(self):

        jsonify(get_paginated_list(

            UserModel,

            'users/page',

            start=request.args.get('start', 1),

            limit=request.args.get('limit', 100)

        ))

The problem i get is when i try get users from link http://127.0.0.1:5000/users/page?start=1&limit=100

TypeError: unhashable type: 'slice'

How to solve this thing? Or how can i show results as i want?

1 Answer

0 votes
by (25.1k points)

The issue is in the get_paginated_list method's last second line. results is not a list, it is a dictionary. So you need to access it like this:

obj['results'] = results['users'][(start - 1):(start - 1 + limit)]

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
2 answers
asked Sep 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...