chore: offload some shared functionality to other methods

should also fix unexpected db behavior (hangs and disconnects)
This commit is contained in:
2025-06-05 16:31:45 +02:00
parent c3a6626d6f
commit 791d20139d
2 changed files with 57 additions and 20 deletions

View File

@@ -58,6 +58,8 @@ def setup():
sanity_string += f" If you're running a reverse proxy, set {c.OKCYAN}is_proxied{c.ENDC} to true to silence this message.\n"
print(sanity_string)
# Should fix disconnects: https://stackoverflow.com/a/61739721
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {"pool_pre_ping": True}
app.config['SQLALCHEMY_DATABASE_URI'] = f"{config['general']['db_path_url']}"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

View File

@@ -36,6 +36,9 @@ class baza():
self.db = self.initDB(self.app, config)
self.refresh_session()
def __repr__(self):
return f"<Obiekt bazodanowy baza ({len(self.entities)} encji)>"
def initDB(self, app, config):
global sportowcy, trofea, sportowcy_w_meczach, statystyki_sportowcow, kluby, mecze
tnp = config['general']['db_prefix'] + "_lewangoalski_"
@@ -201,8 +204,10 @@ class baza():
:param string: Zapis tekstowy
:type string: str
"""
table_str = string[:string.find('.')]
column_str = string[string.find('.') + 1:]
try:
table_str, column_str = string.split('.')
except:
raise ValueError("Nieprawidłowe dane - podaj zarówno tabelę, jak i kolumnę, np.: \"kluby.id_klubu\".")
if hasattr(self.entities[table_str], column_str):
return getattr(self.entities[table_str], column_str)
return None
@@ -222,28 +227,61 @@ class baza():
if not isinstance(entity_type, str):
entity_type = entity_type.__name__
# Save special arguments received with kwargs,
# that are meant for SQL operations to special_args,
# and delete from the rest, that will be passed
# directly to filter_by().
# They will not be passed as search query, but serve
# as an additional search parameter.
special_keywords = ("ORDER_BY", "ORDER_BY_DESC", "LIMIT")
special_args = {}
for arg in special_keywords:
if arg in kwargs:
special_args[arg] = kwargs[arg]
del kwargs[arg]
query_params, special_args = self.extract_special_args(kwargs)
print(f"[{round(time.time())}] SELECT")
results = (
self.session.
query(self.entities[entity_type]).
filter_by(**kwargs)
filter_by(**query_params)
)
# Obsługuje "ORDER_BY", "LIMIT", itp. itd.
results = self.manipulate_results(results, special_args)
results_objs = results.all()
print(f"[{round(time.time())}] SELECT RESULTS: {results_objs}")
return results_objs
def extract_special_args(self, dictionary: dict):
"""
Zwraca krotkę składającą się ze słowników z:
- parametrami wyszukiwania
- specjalnymi argumentami
:param dictionary: Słownik wejściowy
:type dictionary: dict
"""
# Save special arguments received with kwargs,
# that are meant for SQL operations to special_args,
# and delete from the rest, that will be passed
# directly to filter_by().
# They will not be passed as search query, but serve
# as an additional search parameter.
dictionary = dictionary.copy()
special_keywords = ("ORDER_BY", "ORDER_BY_DESC", "LIMIT")
special_args = {}
for arg in special_keywords:
if arg in dictionary:
special_args[arg] = dictionary[arg]
del dictionary[arg]
return dictionary, special_args
def manipulate_results(self, results, special_args: dict):
"""
Wykonuje specjalne operacje na rezultatach wyszukiwania.
:param results: Wyniki wyszukiwania (ORM)
:param special_args: Specjalne operacje
:type special_args: dict
"""
if "ORDER_BY" in special_args:
column = self.str_to_column(special_args["ORDER_BY"])
if column is not None:
@@ -257,10 +295,7 @@ class baza():
if "LIMIT" in special_args:
results = results.limit(special_args["LIMIT"])
results_objs = results.all()
print(f"[{round(time.time())}] SELECT RESULTS: {results_objs}")
return results_objs
return results
@exit_gracefully
def simple_insert_one(self, entity_type, **kwargs):