ki-backend/ki/handlers/find_profiles.py

52 lines
1.7 KiB
Python
Raw Permalink Normal View History

# SPDX-FileCopyrightText: WTF Kooperative eG <https://wtf-eg.de/>
#
# SPDX-License-Identifier: AGPL-3.0-or-later
2021-07-05 18:54:25 +02:00
from flask import make_response, request
2021-08-16 22:41:03 +02:00
from ki.models import Profile, ProfileSkill, Skill, ProfileLanguage, Language
2021-07-05 18:54:25 +02:00
def find_profiles():
2022-01-16 16:35:23 +01:00
try:
page = int(request.args.get("page", 1))
except ValueError:
page = 1
2021-07-05 18:54:25 +02:00
if page < 1:
return make_response({"messages": {"page": "Die angefragte Seite muss mindestens 1 sein"}}, 400)
page_size = int(request.args.get("page_size", 20))
if page_size > 100:
return make_response({"messages": {"page_size": "Die maximale Anzahl Einträge pro Seite beträgt 100"}}, 400)
2021-09-20 21:07:48 +02:00
query = Profile.query.distinct(Profile.id) \
2022-01-16 16:35:23 +01:00
.order_by(Profile.nickname) \
2021-09-20 21:07:48 +02:00
.filter(Profile.visible.is_(True)) \
2021-08-16 22:41:03 +02:00
.join(Profile.skills, isouter=True).join(ProfileSkill.skill, isouter=True) \
.join(Profile.languages, isouter=True).join(ProfileLanguage.language, isouter=True)
if "search" in request.args:
terms = request.args["search"].split(" ")
for term in terms:
query = query.filter(
Profile.nickname.like(f"%{term}%") | Skill.name.like(f"%{term}%") | Language.name.like(f"%{term}%"))
if "nickname" in request.args:
nickname = request.args.get("nickname")
query = query.filter(Profile.nickname.like(f"%{nickname}%"))
2021-07-05 18:54:25 +02:00
2022-01-16 16:35:23 +01:00
paginated_result = query.paginate(page=page, per_page=page_size)
2021-07-05 18:54:25 +02:00
api_profiles = []
2022-01-16 16:35:23 +01:00
for db_profile in paginated_result.items:
2021-07-05 18:54:25 +02:00
api_profiles.append(db_profile.to_dict())
2022-01-16 16:35:23 +01:00
return make_response({
"total": paginated_result.total,
"pages": paginated_result.pages,
"page": paginated_result.page,
"profiles": api_profiles
})