31 lines
902 B
Python
31 lines
902 B
Python
import json
|
|
import os
|
|
import threading
|
|
|
|
|
|
class FileStore:
|
|
def __init__(self, data_dir):
|
|
self.path = os.path.join(data_dir, "measures.json")
|
|
self._lock = threading.Lock()
|
|
os.makedirs(data_dir, exist_ok=True)
|
|
if not os.path.exists(self.path):
|
|
self._write([])
|
|
|
|
def _read(self):
|
|
with open(self.path, "r", encoding="utf-8") as f:
|
|
return json.load(f)
|
|
|
|
def _write(self, data):
|
|
with open(self.path, "w", encoding="utf-8") as f:
|
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
|
|
|
def add_measure(self, measure):
|
|
with self._lock:
|
|
data = self._read()
|
|
data.append(measure)
|
|
self._write(data)
|
|
|
|
def list_measures(self, device_id, limit=50):
|
|
with self._lock:
|
|
data = self._read()
|
|
return [m for m in data if m["device_id"] == device_id][-limit:] |