54 lines
1.5 KiB
Python
54 lines
1.5 KiB
Python
from flask import Blueprint, render_template, request, jsonify
|
|
from sqlalchemy import select
|
|
from the_works.database import db
|
|
import the_works.models
|
|
import inspect
|
|
|
|
bp = Blueprint("home", __name__)
|
|
|
|
# prepare list of DB table classes to be searched by search_all()
|
|
tables = []
|
|
for name, obj in inspect.getmembers(the_works.models):
|
|
if "_" not in name and inspect.isclass(obj):
|
|
tables.append(obj)
|
|
#print(tables) #DEBUG
|
|
|
|
@bp.route("/")
|
|
def startpage():
|
|
return render_template("views/home.html")
|
|
|
|
@bp.route("/search")
|
|
def search_all():
|
|
# return when query is empty
|
|
if not request.args.get("query"):
|
|
return jsonify({})
|
|
|
|
# get URL parameters
|
|
s = request.args.get("query")
|
|
matchCase = True if request.args.get("case").lower() == "match" else False
|
|
result = {}
|
|
|
|
# loop over database tables
|
|
for table in tables:
|
|
text_columns = [column.key for column in table.__table__.columns if type(column.type) == db.types.TEXT]
|
|
hits = []
|
|
# loop over table rows
|
|
for row in db.session.execute(select(table)):
|
|
# loop over each text column in row
|
|
for column in text_columns:
|
|
if row[0].__getattribute__(column) is None:
|
|
continue
|
|
if matchCase:
|
|
if s in row[0].__getattribute__(column):
|
|
hits.append(row[0]._asdict())
|
|
break
|
|
else:
|
|
if s.lower() in row[0].__getattribute__(column).lower():
|
|
hits.append(row[0]._asdict())
|
|
break
|
|
if hits != []:
|
|
result[table.__table__.fullname] = hits
|
|
# return results
|
|
return jsonify(result)
|
|
|