优化数据获取逻辑,处理空数据和异常情况

This commit is contained in:
xiaozhou233 committed 2026-06-29 18:48:21 +08:00
1 parent 2e033886a5
commit e7acd57bad
2 files changed
+42 -11

No files matched your search

+24 -2
View File
@@ -29,7 +29,12 @@ def data_all(token:str):
if token!= TOKEN:
return {"status": "error", "message": "token error"}
return get_data()
data = get_data()
if data is None:
return []
return data
# 获取最新数据
@app.get("/data/last")
@@ -37,7 +42,17 @@ def data_last(token:str):
if token!= TOKEN:
return {"status": "error", "message": "token error"}
return get_last_data()
data = get_last_data()
if data is None:
return {
"time": None,
"ph": None,
"tds": None,
"turbidity": None
}
return data
# 获取最新数据的评分
@app.get("/data/score")
@@ -46,6 +61,13 @@ def data_score(token:str):
return {"status": "error", "message": "token error"}
data = get_last_data()
if data is None:
return {
"code": 1,
"message": "暂无数据"
}
ph = data["ph"]
tds = data["tds"]
turbidity = data["turbidity"]
+18 -9
View File
@@ -24,19 +24,28 @@ def insert_data(time, ph, tds, turbidity):
# 获取所有数据
def get_data():
with open(DATA_FILE, "r", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
data = []
data = []
try:
with open(DATA_FILE, "r", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
row["ph"] = float(row["ph"])
row["tds"] = float(row["tds"])
row["turbidity"] = float(row["turbidity"])
if reader.fieldnames is None:
return []
data.append(row)
for row in reader:
try:
row["ph"] = float(row["ph"])
row["tds"] = float(row["tds"])
row["turbidity"] = float(row["turbidity"])
data.append(row)
except (ValueError, TypeError, KeyError):
continue
return data
except FileNotFoundError:
return []
return data
# 获取最新数据
def get_last_data():