Spaces:
Paused
Paused
File size: 2,769 Bytes
5545e4d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import sqlite3
import json
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(override=True)
# Resolve the database from the project directory, rather than the process
# working directory. The dashboard and the scheduler are often started from
# different directories; a relative path makes each process create/read a
# different database and produces an apparently empty dashboard.
DB = str(Path(__file__).resolve().parents[1] / "accounts.db")
with sqlite3.connect(DB) as conn:
cursor = conn.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS accounts (name TEXT PRIMARY KEY, account TEXT)')
cursor.execute('''
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
datetime DATETIME,
type TEXT,
message TEXT
)
''')
conn.commit()
def write_account(name, account_dict):
json_data = json.dumps(account_dict)
with sqlite3.connect(DB) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO accounts (name, account)
VALUES (?, ?)
ON CONFLICT(name) DO UPDATE SET account=excluded.account
''', (name.lower(), json_data))
conn.commit()
def read_account(name):
with sqlite3.connect(DB) as conn:
cursor = conn.cursor()
cursor.execute('SELECT account FROM accounts WHERE name = ?', (name.lower(),))
row = cursor.fetchone()
return json.loads(row[0]) if row else None
def write_log(name: str, type: str, message: str):
"""
Write a log entry to the logs table.
Args:
name (str): The name associated with the log
type (str): The type of log entry
message (str): The log message
"""
now = datetime.now().isoformat()
with sqlite3.connect(DB) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO logs (name, datetime, type, message)
VALUES (?, datetime('now'), ?, ?)
''', (name.lower(), type, message))
conn.commit()
def read_log(name: str, last_n=10):
"""
Read the most recent log entries for a given name.
Args:
name (str): The name to retrieve logs for
last_n (int): Number of most recent entries to retrieve
Returns:
list: A list of tuples containing (datetime, type, message)
"""
with sqlite3.connect(DB) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT datetime, type, message FROM logs
WHERE name = ?
ORDER BY id DESC
LIMIT ?
''', (name.lower(), last_n))
return reversed(cursor.fetchall())
|