EOS/server_load_profile.py

68 lines
2.0 KiB
Python
Raw Normal View History

2024-02-16 15:27:56 +01:00
from datetime import datetime
2024-02-18 13:24:09 +01:00
from pprint import pprint
2024-02-16 15:27:56 +01:00
2024-10-03 11:05:44 +02:00
from flask import Flask, jsonify, request
import modules.class_load as cl
2024-02-16 15:27:56 +01:00
app = Flask(__name__)
# Constants
2024-10-03 11:05:44 +02:00
DATE_FORMAT = "%Y-%m-%d"
EXPECTED_ARRAY_SHAPE = (2, 24)
2024-10-03 11:05:44 +02:00
FILEPATH = r".\load_profiles.npz"
2024-02-16 15:27:56 +01:00
def get_load_forecast(year_energy):
"""Initialize LoadForecast with the given year_energy."""
return cl.LoadForecast(filepath=FILEPATH, year_energy=float(year_energy))
2024-10-03 11:05:44 +02:00
def validate_date(date_str):
"""Validate the date string and return a datetime object."""
try:
return datetime.strptime(date_str, DATE_FORMAT)
except ValueError:
2024-10-03 11:05:44 +02:00
raise ValueError(
"Date is not in the correct format. Expected format: YYYY-MM-DD."
)
2024-02-16 15:27:56 +01:00
2024-10-03 11:05:44 +02:00
@app.route("/getdata", methods=["GET"])
2024-02-16 15:27:56 +01:00
def get_data():
# Retrieve the date and year_energy from query parameters
2024-10-03 11:05:44 +02:00
date_str = request.args.get("date")
year_energy = request.args.get("year_energy")
if not date_str or not year_energy:
2024-10-03 11:05:44 +02:00
return jsonify(
{"error": "Missing 'date' or 'year_energy' query parameter."}
), 400
2024-02-16 15:27:56 +01:00
try:
# Validate and convert the date
date_obj = validate_date(date_str)
lf = get_load_forecast(year_energy)
# Get daily statistics for the requested date
2024-02-18 13:24:09 +01:00
array_list = lf.get_daily_stats(date_str)
pprint(array_list)
pprint(array_list.shape)
# Check if the shape of the array is valid
if array_list.shape == EXPECTED_ARRAY_SHAPE:
2024-02-18 13:24:09 +01:00
return jsonify({date_str: array_list.tolist()})
2024-02-16 15:27:56 +01:00
else:
return jsonify({"error": "Data not found for the given date."}), 404
except ValueError as e:
# Return a descriptive error message for date validation issues
return jsonify({"error": str(e)}), 400
except Exception:
# Return a generic error message for unexpected errors
return jsonify({"error": "An unexpected error occurred."}), 500
2024-02-16 15:27:56 +01:00
2024-10-03 11:05:44 +02:00
if __name__ == "__main__":
2024-02-16 15:27:56 +01:00
app.run(debug=True)