diff options
| -rwxr-xr-x | salis.py | 23 |
1 files changed, 14 insertions, 9 deletions
@@ -1,5 +1,6 @@ #!/usr/bin/env -S PYTHONDONTWRITEBYTECODE=1 python +import contextlib import datetime import json import os @@ -318,11 +319,6 @@ if args.command in ["serve"]: class Handler(SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): - self.db_con = sqlite3.connect(sim_db, timeout=600) - self.db_con.row_factory = sqlite3.Row - self.db_con.enable_load_extension(True) - self.db_con.execute("PRAGMA journal_mode=wal;") - self.db_con.execute(f"SELECT load_extension('{sqlx_so}');") super().__init__(*args, **kwargs, directory="data") def log_message(_, format, *args): @@ -344,6 +340,17 @@ if args.command in ["serve"]: self.send_200_and_mime_type(mime_type) with open(path, "r") as f: self.wfile.write(f.read().encode("utf-8")) + @staticmethod + @contextlib.contextmanager + def sqlite_connect(): + db_con = sqlite3.connect(sim_db, timeout=600) + db_con.row_factory = sqlite3.Row + db_con.enable_load_extension(True) + db_con.execute("PRAGMA journal_mode=wal;") + db_con.execute(f"SELECT load_extension('{sqlx_so}');") + try: yield db_con + finally: db_con.close() + def do_GET(self): bits = urllib.parse.urlparse(self.path) @@ -372,21 +379,19 @@ if args.command in ["serve"]: selects = "*" sql_query = f"SELECT * FROM (SELECT rowid, {selects} FROM {table} WHERE {x_axis} >= {x_low} AND {x_axis} <= {x_high} AND rowid % {nth} == 0 ORDER BY {x_axis} DESC LIMIT {entries}) ORDER BY {x_axis} ASC;" - sql_res = self.db_con.execute(sql_query) - sql_list = [dict(row) for row in sql_res.fetchall()] + with Handler.sqlite_connect() as db_con: sql_list = [dict(row) for row in db_con.execute(sql_query).fetchall()] return self.send_as_json(sql_list) if bits.path == "/x_high": http_query = urllib.parse.parse_qs(bits.query) x_axis = http_query["x_axis"][0] sql_query = f"SELECT {x_axis} as x_high FROM general ORDER BY {x_axis} DESC LIMIT 1;" - sql_dict = dict(self.db_con.execute(sql_query).fetchone()) + with Handler.sqlite_connect() as db_con: sql_dict = dict(db_con.execute(sql_query).fetchone()) return self.send_as_json(sql_dict) self.log_error(f"Unsupported endpoint: {bits.path}") self.send_response(400) self.end_headers() - self.db_con.close() info("Launching data server") server = ThreadingHTTPServer(("", args.port), Handler) |
