2024-02-16 15:27:56 +01:00
|
|
|
from flask import Flask, jsonify, request
|
|
|
|
import numpy as np
|
|
|
|
from datetime import datetime
|
2024-02-18 13:24:09 +01:00
|
|
|
import modules.class_load as cl
|
|
|
|
from pprint import pprint
|
2024-02-16 15:27:56 +01:00
|
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
2024-09-20 11:51:34 +02:00
|
|
|
# Constants
|
|
|
|
DATE_FORMAT = '%Y-%m-%d'
|
|
|
|
EXPECTED_ARRAY_SHAPE = (2, 24)
|
|
|
|
FILEPATH = r'.\load_profiles.npz'
|
2024-02-16 15:27:56 +01:00
|
|
|
|
2024-09-20 11:51:34 +02:00
|
|
|
def get_load_forecast(year_energy):
|
|
|
|
"""Initialize LoadForecast with the given year_energy."""
|
|
|
|
return cl.LoadForecast(filepath=FILEPATH, year_energy=float(year_energy))
|
|
|
|
|
|
|
|
def validate_date(date_str):
|
|
|
|
"""Validate the date string and return a datetime object."""
|
|
|
|
try:
|
|
|
|
return datetime.strptime(date_str, DATE_FORMAT)
|
|
|
|
except ValueError:
|
|
|
|
raise ValueError("Date is not in the correct format. Expected format: YYYY-MM-DD.")
|
2024-02-16 15:27:56 +01:00
|
|
|
|
|
|
|
@app.route('/getdata', methods=['GET'])
|
|
|
|
def get_data():
|
2024-09-20 11:51:34 +02:00
|
|
|
# Retrieve the date and year_energy from query parameters
|
2024-02-16 15:27:56 +01:00
|
|
|
date_str = request.args.get('date')
|
|
|
|
year_energy = request.args.get('year_energy')
|
2024-09-20 11:51:34 +02:00
|
|
|
|
|
|
|
if not date_str or not year_energy:
|
|
|
|
return jsonify({"error": "Missing 'date' or 'year_energy' query parameter."}), 400
|
|
|
|
|
2024-02-16 15:27:56 +01:00
|
|
|
try:
|
2024-09-20 11:51:34 +02:00
|
|
|
# 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)
|
2024-09-20 11:51:34 +02:00
|
|
|
|
|
|
|
# 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:
|
2024-09-20 11:51:34 +02:00
|
|
|
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
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
app.run(debug=True)
|