-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_db.py
More file actions
52 lines (46 loc) · 1.46 KB
/
sqlite_db.py
File metadata and controls
52 lines (46 loc) · 1.46 KB
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
import os
import sqlite3
from datetime import datetime, timezone
DB_PATH = os.getenv("SQLITE_DB_PATH", "app.db")
if os.getenv("GAE_ENV", "").startswith("standard"):
DB_PATH = os.path.join("/tmp", DB_PATH)
def get_connection():
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
return connection
def init_db():
with get_connection() as connection:
connection.execute(
"""
CREATE TABLE IF NOT EXISTS event_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts_utc TEXT NOT NULL,
user_email TEXT,
action TEXT NOT NULL,
pack_id TEXT,
meta TEXT
);
"""
)
connection.commit()
def log_event(action, user_email=None, pack_id=None, meta=None):
timestamp = datetime.now(timezone.utc).isoformat()
with get_connection() as connection:
connection.execute(
"INSERT INTO event_log (ts_utc, user_email, action, pack_id, meta) VALUES (?, ?, ?, ?, ?)",
(timestamp, user_email, action, pack_id, meta)
)
connection.commit()
def get_recent_events(limit: int = 100):
connection = get_connection()
rows = connection.execute(
"""
SELECT id, ts_utc, user_email, action, pack_id, meta
FROM event_log
ORDER BY id DESC
LIMIT ?
""",
(limit,)
).fetchall()
connection.close()
return rows