我对分页有疑问。如果我只用字典列表尝试它就可以了,当我尝试使用数据库中的模型时,问题就开始了。我的sql alchemy数据库中有大约1万名用户。用户是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)
我想向用户显示1到100,从100到200等。我正在尝试使用本教程:https://aviaryan.com/blog/gsoc/paginated-apis-flask
这里是将模型返回到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()))}
这是分页定义:
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
我的api资源代码是:
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)
))
我遇到的问题是,当我尝试从链接http://127.0.0.1:5000/users/page?start=1&limit=100获取用户时
TypeError:不可散列的类型:'slice'
该如何解决?或者如何显示我想要的结果?
答案 0 :(得分:1)
可能是错误在这里:
obj['results'] = results[(start - 1):(start - 1 + limit)]
results不是列表,函数return_all
返回类似{'users': []}
的字典
所以尝试这样的事情:
obj['results'] = results['users'][(start - 1):(start - 1 + limit)]