feat: Implement webserver with endpoint to return newest CSV entry as JSON
This commit is contained in:
parent
2425a4cf7c
commit
b83f70c354
50
html_data_format/webserver.py
Normal file
50
html_data_format/webserver.py
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
import json
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from bottle import route, run, request, response
|
||||||
|
from personal_data.csv_import import load_csv_file
|
||||||
|
|
||||||
|
logger = logging.getLogger("webserver")
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
def parse_time(time_str: str) -> datetime.datetime:
|
||||||
|
"""
|
||||||
|
Parse a time string assuming ISO-8601 format.
|
||||||
|
Adjust this parser if your CSV timestamps differ.
|
||||||
|
"""
|
||||||
|
return datetime.datetime.fromisoformat(time_str)
|
||||||
|
|
||||||
|
@route('/newest')
|
||||||
|
def newest_entry():
|
||||||
|
"""
|
||||||
|
Loads a CSV file (default: data.csv, overridable by query param 'file'),
|
||||||
|
finds the newest entry based on the 'time.current' column, and returns it as JSON.
|
||||||
|
"""
|
||||||
|
file_param = request.query.get("file", "data.csv")
|
||||||
|
csv_path = Path(file_param)
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = load_csv_file(csv_path)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error loading CSV file at {csv_path}: {e}")
|
||||||
|
response.status = 500
|
||||||
|
return {"error": f"Failed to load CSV: {str(e)}"}
|
||||||
|
|
||||||
|
if not data:
|
||||||
|
response.status = 404
|
||||||
|
return {"error": "CSV file is empty or no data found"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
newest = max(data, key=lambda r: parse_time(r['time.current']))
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Error processing CSV data: {e}")
|
||||||
|
response.status = 500
|
||||||
|
return {"error": f"Failed to process CSV data: {str(e)}"}
|
||||||
|
|
||||||
|
response.content_type = "application/json"
|
||||||
|
return json.dumps(newest)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
run(host='localhost', port=8080, debug=True)
|
Loading…
Reference in New Issue
Block a user