Create services/detection-service/main.py
Browse files
services/detection-service/main.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
import psycopg2
|
| 6 |
+
import redis
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
|
| 10 |
+
load_dotenv()
|
| 11 |
+
DATABASE_URL = os.getenv("DATABASE_URL")
|
| 12 |
+
REDIS_URL = os.getenv("REDIS_URL")
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
r = redis.from_url(REDIS_URL)
|
| 16 |
+
|
| 17 |
+
def get_conn():
|
| 18 |
+
return psycopg2.connect(DATABASE_URL)
|
| 19 |
+
|
| 20 |
+
class Detection(BaseModel):
|
| 21 |
+
namespace: str
|
| 22 |
+
type: str
|
| 23 |
+
timestamp: str = None
|
| 24 |
+
location: dict
|
| 25 |
+
severity: int = 1
|
| 26 |
+
images: list = []
|
| 27 |
+
provenance: dict = {}
|
| 28 |
+
|
| 29 |
+
@app.post("/detect")
|
| 30 |
+
def detect(d: Detection):
|
| 31 |
+
ts = d.timestamp or datetime.utcnow().isoformat()
|
| 32 |
+
try:
|
| 33 |
+
conn = get_conn()
|
| 34 |
+
cur = conn.cursor()
|
| 35 |
+
cur.execute(
|
| 36 |
+
"INSERT INTO objects (namespace,type,timestamp,location,severity,images,provenance) VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
| 37 |
+
(d.namespace, d.type, ts, json.dumps(d.location), d.severity, json.dumps(d.images), json.dumps(d.provenance))
|
| 38 |
+
)
|
| 39 |
+
new_id = cur.fetchone()[0]
|
| 40 |
+
conn.commit()
|
| 41 |
+
cur.close()
|
| 42 |
+
conn.close()
|
| 43 |
+
# publish event
|
| 44 |
+
ev = {"id": str(new_id), "namespace": d.namespace, "type": d.type, "location": d.location, "severity": d.severity}
|
| 45 |
+
r.publish("infra:faults:created", json.dumps(ev))
|
| 46 |
+
return {"id": str(new_id)}
|
| 47 |
+
except Exception as e:
|
| 48 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 49 |
+
|