1
0
personal-data/html_data_format/webserver.py

55 lines
1.5 KiB
Python

import datetime
import json
import logging
from pathlib import Path
from bottle import request, response, route, run
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)