add pagination

This commit is contained in:
2022-01-16 16:35:23 +01:00
parent a3919d5d51
commit be9bc8b5cc
3 changed files with 34 additions and 18 deletions

View File

@ -8,7 +8,10 @@ from ki.models import Profile, ProfileSkill, Skill, ProfileLanguage, Language
def find_profiles():
page = int(request.args.get("page", 1))
try:
page = int(request.args.get("page", 1))
except ValueError:
page = 1
if page < 1:
return make_response({"messages": {"page": "Die angefragte Seite muss mindestens 1 sein"}}, 400)
@ -19,6 +22,7 @@ def find_profiles():
return make_response({"messages": {"page_size": "Die maximale Anzahl Einträge pro Seite beträgt 100"}}, 400)
query = Profile.query.distinct(Profile.id) \
.order_by(Profile.nickname) \
.filter(Profile.visible.is_(True)) \
.join(Profile.skills, isouter=True).join(ProfileSkill.skill, isouter=True) \
.join(Profile.languages, isouter=True).join(ProfileLanguage.language, isouter=True)
@ -33,13 +37,15 @@ def find_profiles():
nickname = request.args.get("nickname")
query = query.filter(Profile.nickname.like(f"%{nickname}%"))
count = query.count()
offset = (page - 1) * page_size
db_profiles = query.limit(page_size).offset(offset).all()
paginated_result = query.paginate(page=page, per_page=page_size)
api_profiles = []
for db_profile in db_profiles:
for db_profile in paginated_result.items:
api_profiles.append(db_profile.to_dict())
return make_response({"total": count, "profiles": api_profiles})
return make_response({
"total": paginated_result.total,
"pages": paginated_result.pages,
"page": paginated_result.page,
"profiles": api_profiles
})