-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
64 lines (51 loc) · 1.8 KB
/
Copy pathmain.py
File metadata and controls
64 lines (51 loc) · 1.8 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
53
54
55
56
57
58
59
60
61
62
63
64
from fastapi import FastAPI, Depends
from fastapi.responses import FileResponse
from pydantic import BaseModel
import sqlite3
import uvicorn
from datetime import timezone, datetime, timedelta
from ml_analysis import perform_analysis_and_generate_chart
class Event(BaseModel):
userid: str
eventname: str
app = FastAPI()
def get_db_connection():
return sqlite3.connect('../events.db', check_same_thread=False)
def create_events_table():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS events (
eventtimestamputc DATETIME,
userid TEXT,
eventname TEXT
)
''')
conn.commit()
conn.close()
create_events_table()
@app.post("/process_event/")
async def process_event(event: Event, db=Depends(get_db_connection)):
cursor = db.cursor()
cursor.execute('''
INSERT INTO events (eventtimestamputc, userid, eventname) VALUES (CURRENT_TIMESTAMP, ?, ?)
''', (event.userid, event.eventname))
db.commit()
db.close()
return {"message": "Event processed successfully"}
@app.post("/get_reports/")
async def get_reports(lastseconds: int, userid: str, db=Depends(get_db_connection)):
cursor = db.cursor()
cursor.execute('''
SELECT * FROM events WHERE userid = ? AND eventtimestamputc > DATETIME('now', ?)
''', (userid, f'-{lastseconds} seconds'))
events = cursor.fetchall()
db.close()
events_list = [{'eventtimestamputc': event[0], 'userid': event[1], 'eventname': event[2]} for event in events]
return {"events": events_list}
@app.get('/analyze_events')
async def analyze_events():
chart_path = ml_analysis.perform_analysis_and_generate_chart()
return FileResponse(chart_path, media_type='image/png')
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)