user10646715
user10646715

Reputation:

FlaskRestful pagination TypeError: unhashable type: 'slice'

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?

Upvotes: 0

Views: 636

Answers (1)

Kubas
Kubas

Reputation: 1028

Probably bug is here:

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

results is not a list, function return_all returns dict like {'users': []}

so try something like this:

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

Upvotes: 1

Related Questions