ki-backend/ki/routes.py

88 lines
2.1 KiB
Python
Raw Normal View History

2021-06-07 18:52:30 +02:00
import os
from flask import make_response, request, send_file
2021-06-07 17:52:14 +02:00
from ki.models import Language, Skill
2021-06-06 22:25:10 +02:00
from app import app
2021-06-07 17:52:14 +02:00
def models_to_list(models):
models_list = []
for model in models:
models_list.append(model.to_dict())
return models_list
def handle_completion_request(model, key):
query = model.query
2021-06-07 17:52:14 +02:00
if "search" in request.args:
query = query.filter(model.name.startswith(request.args.get("search")))
2021-06-07 17:52:14 +02:00
results = query.order_by(model.name) \
2021-06-07 17:52:14 +02:00
.limit(10) \
.all()
api_results = models_to_list(results)
response_data = {}
response_data[key] = api_results
2021-06-07 17:52:14 +02:00
return response_data
2021-06-07 18:52:30 +02:00
def handle_icon_request(model, id, path):
object = model.query.get(id)
if object is None:
return make_response({}, 404)
2021-06-07 18:52:30 +02:00
icon_base_path = path + str(id)
2021-06-07 18:52:30 +02:00
icon_svg_path = icon_base_path + ".svg"
if os.path.exists(icon_svg_path):
return send_file(icon_svg_path, mimetype="image/svg")
icon_png_path = icon_base_path + ".png"
if os.path.exists(icon_png_path):
return send_file(icon_png_path, mimetype="image/png")
unknown_svg_path = path + "unknown.svg"
if os.path.exists(unknown_svg_path):
return send_file(unknown_svg_path, mimetype="image/svg")
unknown_png_path = path + "unknown.png"
if os.path.exists(unknown_png_path):
return send_file(unknown_png_path, mimetype="image/png")
return make_response({"error": "icon not found"}, 404)
@app.route("/")
def hello_world():
return "KI"
@app.route("/skills")
def get_skills():
return handle_completion_request(Skill, "skills")
@app.route("/skills/<skill_id>/icon")
def get_skill_icon(skill_id):
skill_icons_path = app.config["KI_DATA_DIR"] + "/imgs/skill_icons/"
return handle_icon_request(Skill, skill_id, skill_icons_path)
@app.route("/languages")
def get_languages():
return handle_completion_request(Language, "languages")
2021-06-07 18:52:30 +02:00
@app.route("/languages/<language_id>/icon")
def get_language_icon(language_id):
language_flags_path = app.config["KI_DATA_DIR"] + "/imgs/flags/"
return handle_icon_request(Language, language_id, language_flags_path)