mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 23:16:18 +01:00
fix: unify mypy environments for local checks and CI (#1291)
The isolated pre-commit mypy hook previously omitted runtime type information that make mypy used, hiding errors involving dependencies such as Pydantic and Pendulum. Makefile, pre-commit and CI now run the same full-project typing policy in the development environment defined by uv.lock. - Use uv run --locked --exact --extra dev and the same mypy arguments for Makefile and the local hook. Check all of src and tests, including on configuration-only changes. - Pin Python 3.13 for local development and the pre-commit CI job, and install the locked pre-commit version in CI. - Disable incremental analysis because existing Pendulum cache state changes mypy 2.3.1 diagnostics. Document the policy, the performance tradeoff and the existing typing debt. - Add a regression test that exercises Makefile, the hook and the CI command in a temporary project, accepting valid dependency types and detecting deliberate Pydantic/Pendulum assignment errors. Resolve the newly detected mypy diagnostics. - Enable the numpydantic and Pydantic mypy plugins, retaining strict Pydantic constructor typing with init_typed = true. Validate raw/coercible payloads through model_validate. - Propagate concrete record, provider and time-window types through generic collections, factories and lookup methods. Preserve runtime field inspection and generated time-window documentation. - Align Pendulum annotations with actual factory/arithmetic results while retaining Pydantic validation adapters at runtime. Correct optional values, array boundaries, REST handlers and plotting interfaces. - Add pinned scipy-stubs and types-psutil, update uv.lock, and supply the plugins' dependencies. - Add runtime regression coverage for validated path defaults, normalized time-series metadata, generic field inspection, invalid timestamps and unsupported provider imports. Runtime and compatibility details: - Validate path defaults as Path objects while retaining raw string defaults needed by migration serialization with exclude_defaults. - Normalize feed-in tariff lists and default charge rates to NumPy arrays; reject missing timestamps/uninitialized values explicitly. Importing into a provider without import support returns HTTP 400. - Public JSON schemas and OpenAPI structure match main (excluding the generated version). Signed-off-by: dr-dimitry Signed-off-by: dr-dimitry Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com> Co-authored-by: dr-dimitri <87113560+dr-dimitri@users.noreply.github.com> Co-authored-by: Normann <github@koldrack.com>
This commit is contained in:
co-authored by
dr-dimitri
Normann
parent
5b584cbb57
commit
1abdd345c4
@@ -1,12 +1,18 @@
|
||||
# Module taken from https://github.com/koaning/fh-altair
|
||||
# MIT license
|
||||
from typing import Optional
|
||||
from typing import Callable, Optional, cast
|
||||
|
||||
from bokeh.embed import components
|
||||
from bokeh.models import Plot
|
||||
from bokeh.models.annotations import Title
|
||||
from bokeh.plotting import figure
|
||||
from bokeh.resources import INLINE
|
||||
from monsterui.franken import H4, Card, NotStr
|
||||
|
||||
# Bokeh accepts FigureOptions as constructor keywords, but its generated
|
||||
# constructor signature only lists model properties. Preserve the typed result.
|
||||
create_figure = cast(Callable[..., figure], figure)
|
||||
|
||||
# Javascript for bokeh - to be included by the page
|
||||
BokehJS = [NotStr(INLINE.render_css()), NotStr(INLINE.render_js())]
|
||||
|
||||
@@ -29,7 +35,7 @@ def bokey_apply_theme_to_plot(plot: Plot, dark: bool) -> None:
|
||||
if dark:
|
||||
plot.background_fill_color = "#1e1e1e"
|
||||
plot.border_fill_color = "#1e1e1e"
|
||||
plot.title.text_color = "white"
|
||||
cast(Title, plot.title).text_color = "white"
|
||||
for ax in plot.xaxis + plot.yaxis:
|
||||
ax.axis_line_color = "white"
|
||||
ax.major_tick_line_color = "white"
|
||||
@@ -44,7 +50,7 @@ def bokey_apply_theme_to_plot(plot: Plot, dark: bool) -> None:
|
||||
else:
|
||||
plot.background_fill_color = "white"
|
||||
plot.border_fill_color = "white"
|
||||
plot.title.text_color = "black"
|
||||
cast(Title, plot.title).text_color = "black"
|
||||
for ax in plot.xaxis + plot.yaxis:
|
||||
ax.axis_line_color = "black"
|
||||
ax.major_tick_line_color = "black"
|
||||
|
||||
@@ -59,7 +59,7 @@ def item_model_defaults(item_model: Any) -> tuple[dict, list[str]]:
|
||||
if field_info.default is not PydanticUndefined:
|
||||
kwargs[field_name] = field_info.default
|
||||
elif field_info.default_factory is not None:
|
||||
kwargs[field_name] = field_info.default_factory()
|
||||
kwargs[field_name] = field_info.get_default(call_default_factory=True)
|
||||
else:
|
||||
required_missing.append(field_name)
|
||||
|
||||
|
||||
@@ -192,7 +192,7 @@ def get_default_value(field_info: Union[FieldInfo, ComputedFieldInfo], regular_f
|
||||
"""
|
||||
import pathlib
|
||||
|
||||
if not regular_field:
|
||||
if not regular_field or not isinstance(field_info, FieldInfo):
|
||||
return "N/A"
|
||||
|
||||
# Resolve the raw default — prefer plain default, fall back to factory
|
||||
@@ -200,7 +200,7 @@ def get_default_value(field_info: Union[FieldInfo, ComputedFieldInfo], regular_f
|
||||
val = field_info.default
|
||||
elif field_info.default_factory is not None:
|
||||
try:
|
||||
val = field_info.default_factory()
|
||||
val = field_info.get_default(call_default_factory=True)
|
||||
except Exception:
|
||||
return ""
|
||||
else:
|
||||
@@ -250,12 +250,12 @@ def resolve_nested_types(field_type: Any, parent_types: list[str]) -> list[tuple
|
||||
|
||||
|
||||
def create_config_details(
|
||||
model: type[PydanticBaseModel], values: dict, values_prefix: list[str] = []
|
||||
model: type[PydanticBaseModel] | type[ConfigEOS], values: dict, values_prefix: list[str] = []
|
||||
) -> dict[str, dict]:
|
||||
"""Generate configuration details based on provided values and model metadata.
|
||||
|
||||
Args:
|
||||
model (type[PydanticBaseModel]): The Pydantic model to extract configuration from.
|
||||
model: An EOS model or the top-level settings class to extract configuration from.
|
||||
values (dict): A dictionary containing the current configuration values.
|
||||
values_prefix (list[str]): A list of parent type names that prefixes the model values in the values.
|
||||
|
||||
@@ -271,7 +271,11 @@ def create_config_details(
|
||||
) -> None:
|
||||
nonlocal values, values_prefix
|
||||
regular_field = isinstance(subfield_info, FieldInfo)
|
||||
subtype = subfield_info.annotation if regular_field else subfield_info.return_type
|
||||
subtype = (
|
||||
subfield_info.annotation
|
||||
if isinstance(subfield_info, FieldInfo)
|
||||
else subfield_info.return_type
|
||||
)
|
||||
|
||||
nested_types = resolve_nested_types(subtype, [])
|
||||
found_basic = False
|
||||
|
||||
@@ -9,6 +9,7 @@ from fasthtml.common import FT, Div, NotStr
|
||||
from markdown_it import MarkdownIt
|
||||
from markdown_it.renderer import RendererHTML
|
||||
from markdown_it.token import Token
|
||||
from markdown_it.utils import OptionsDict
|
||||
from monsterui.foundations import stringify
|
||||
|
||||
# Where to find the static data assets
|
||||
@@ -42,7 +43,7 @@ def file_to_data_uri(file_path: Path) -> str:
|
||||
|
||||
|
||||
def render_heading(
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: dict, env: dict
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: OptionsDict, env: dict
|
||||
) -> str:
|
||||
"""Custom renderer for Markdown headings with MonsterUI styling."""
|
||||
if tokens[idx].markup == "#":
|
||||
@@ -63,7 +64,7 @@ def render_heading(
|
||||
|
||||
|
||||
def render_paragraph(
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: dict, env: dict
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: OptionsDict, env: dict
|
||||
) -> str:
|
||||
"""Custom renderer for Markdown paragraphs with MonsterUI styling."""
|
||||
tokens[idx].attrSet("class", "leading-7 [&:not(:first-child)]:mt-6")
|
||||
@@ -71,28 +72,30 @@ def render_paragraph(
|
||||
|
||||
|
||||
def render_blockquote(
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: dict, env: dict
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: OptionsDict, env: dict
|
||||
) -> str:
|
||||
"""Custom renderer for Markdown blockquotes with MonsterUI styling."""
|
||||
tokens[idx].attrSet("class", "mt-6 border-l-2 pl-6 italic border-primary")
|
||||
return self.renderToken(tokens, idx, options, env)
|
||||
|
||||
|
||||
def render_list(self: RendererHTML, tokens: List[Token], idx: int, options: dict, env: dict) -> str:
|
||||
def render_list(
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: OptionsDict, env: dict
|
||||
) -> str:
|
||||
"""Custom renderer for lists with MonsterUI styling."""
|
||||
tokens[idx].attrSet("class", "my-6 ml-6 list-disc [&>li]:mt-2")
|
||||
return self.renderToken(tokens, idx, options, env)
|
||||
|
||||
|
||||
def render_image(
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: dict, env: dict
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: OptionsDict, env: dict
|
||||
) -> str:
|
||||
"""Custom renderer for Markdown images with MonsterUI styling."""
|
||||
token = tokens[idx]
|
||||
src = token.attrGet("src")
|
||||
alt = token.content or ""
|
||||
|
||||
if src:
|
||||
if isinstance(src, str) and src:
|
||||
pos = src.find(ASSETS_PREFIX)
|
||||
if pos != -1:
|
||||
asset_rel = src[pos + len(ASSETS_PREFIX) :]
|
||||
@@ -107,12 +110,14 @@ def render_image(
|
||||
return self.renderToken(tokens, idx, options, env)
|
||||
|
||||
|
||||
def render_link(self: RendererHTML, tokens: List[Token], idx: int, options: dict, env: dict) -> str:
|
||||
def render_link(
|
||||
self: RendererHTML, tokens: List[Token], idx: int, options: OptionsDict, env: dict
|
||||
) -> str:
|
||||
"""Custom renderer for Markdown links with MonsterUI styling."""
|
||||
token = tokens[idx]
|
||||
href = token.attrGet("href")
|
||||
|
||||
if href:
|
||||
if isinstance(href, str) and href:
|
||||
pos = href.find(ASSETS_PREFIX)
|
||||
if pos != -1:
|
||||
asset_rel = href[pos + len(ASSETS_PREFIX) :]
|
||||
|
||||
@@ -3,7 +3,6 @@ from typing import Optional, Union
|
||||
import pandas as pd
|
||||
import requests
|
||||
from bokeh.models import ColumnDataSource, LinearAxis, Range1d
|
||||
from bokeh.plotting import figure
|
||||
from loguru import logger
|
||||
from monsterui.franken import (
|
||||
Card,
|
||||
@@ -28,7 +27,11 @@ from akkudoktoreos.core.emplan import (
|
||||
OMBCInstruction,
|
||||
)
|
||||
from akkudoktoreos.optimization.optimization import OptimizationSolution
|
||||
from akkudoktoreos.server.dash.bokeh import Bokeh, bokey_apply_theme_to_plot
|
||||
from akkudoktoreos.server.dash.bokeh import (
|
||||
Bokeh,
|
||||
bokey_apply_theme_to_plot,
|
||||
create_figure,
|
||||
)
|
||||
from akkudoktoreos.server.dash.components import Error
|
||||
from akkudoktoreos.server.dash.context import request_url_for
|
||||
from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime
|
||||
@@ -259,21 +262,21 @@ def SolutionCard(solution: OptimizationSolution, config: SettingsEOS, data: Opti
|
||||
last_run_datetime = "unknown"
|
||||
start_datetime = "unknown"
|
||||
|
||||
plot = figure(
|
||||
plot = create_figure(
|
||||
title=f"Optimization Solution - last run: {last_run_datetime}",
|
||||
x_axis_type="datetime",
|
||||
x_axis_label=f"Datetime [localtime {date_time_tz}] - start: {start_datetime}",
|
||||
y_axis_label="Power [W]",
|
||||
sizing_mode="stretch_width",
|
||||
y_range=Range1d(power_w_min, power_w_max),
|
||||
y_range=Range1d(start=power_w_min, end=power_w_max),
|
||||
height=400,
|
||||
)
|
||||
|
||||
plot.extra_y_ranges = {
|
||||
"energy": Range1d(energy_wh_min, energy_wh_max), # y2
|
||||
"factor": Range1d(factor_min, factor_max), # y3
|
||||
"amt_kwh": Range1d(amt_kwh_min, amt_kwh_max), # y4
|
||||
"amt": Range1d(amt_min, amt_max), # y5
|
||||
"energy": Range1d(start=energy_wh_min, end=energy_wh_max), # y2
|
||||
"factor": Range1d(start=factor_min, end=factor_max), # y3
|
||||
"amt_kwh": Range1d(start=amt_kwh_min, end=amt_kwh_max), # y4
|
||||
"amt": Range1d(start=amt_min, end=amt_max), # y5
|
||||
}
|
||||
# y2 axis
|
||||
y2_axis = LinearAxis(y_range_name="energy", axis_label="Energy [Wh]")
|
||||
@@ -536,7 +539,7 @@ def InstructionCard(
|
||||
)
|
||||
):
|
||||
# This is a battery
|
||||
if instruction.operation_mode_id in ("CHARGE",):
|
||||
if getattr(instruction, "operation_mode_id", None) in ("CHARGE",):
|
||||
icon = "battery-charging"
|
||||
else:
|
||||
icon = "battery"
|
||||
|
||||
@@ -3,11 +3,14 @@ from typing import Optional, Union
|
||||
import pandas as pd
|
||||
import requests
|
||||
from bokeh.models import ColumnDataSource, LinearAxis, Range1d
|
||||
from bokeh.plotting import figure
|
||||
from monsterui.franken import FT, Grid, P
|
||||
|
||||
from akkudoktoreos.core.pydantic import PydanticDateTimeSeries
|
||||
from akkudoktoreos.server.dash.bokeh import Bokeh, bokey_apply_theme_to_plot
|
||||
from akkudoktoreos.server.dash.bokeh import (
|
||||
Bokeh,
|
||||
bokey_apply_theme_to_plot,
|
||||
create_figure,
|
||||
)
|
||||
from akkudoktoreos.server.dash.components import Error
|
||||
|
||||
# bar width for 15 minutes bars (time given in millseconds)
|
||||
@@ -18,7 +21,7 @@ def PVForecast(predictions: pd.DataFrame, config: dict, date_time_tz: str, dark:
|
||||
source = ColumnDataSource(predictions)
|
||||
provider = config["pvforecast"]["provider"]
|
||||
|
||||
plot = figure(
|
||||
plot = create_figure(
|
||||
x_axis_type="datetime",
|
||||
title=f"PV Power Prediction ({provider})",
|
||||
x_axis_label=f"Datetime [localtime {date_time_tz}]",
|
||||
@@ -46,7 +49,7 @@ def ElectricityPriceForecast(
|
||||
source = ColumnDataSource(predictions)
|
||||
provider = config["elecprice"]["provider"]
|
||||
|
||||
plot = figure(
|
||||
plot = create_figure(
|
||||
x_axis_type="datetime",
|
||||
y_range=Range1d(
|
||||
predictions["elecprice_marketprice_kwh"].min() - 0.1,
|
||||
@@ -78,7 +81,7 @@ def WeatherTempAirHumidityForecast(
|
||||
source = ColumnDataSource(predictions)
|
||||
provider = config["weather"]["provider"]
|
||||
|
||||
plot = figure(
|
||||
plot = create_figure(
|
||||
x_axis_type="datetime",
|
||||
title=f"Air Temperature and Humidity Prediction ({provider})",
|
||||
x_axis_label=f"Datetime [localtime {date_time_tz}]",
|
||||
@@ -115,7 +118,7 @@ def WeatherIrradianceForecast(
|
||||
source = ColumnDataSource(predictions)
|
||||
provider = config["weather"]["provider"]
|
||||
|
||||
plot = figure(
|
||||
plot = create_figure(
|
||||
x_axis_type="datetime",
|
||||
title=f"Irradiance Prediction ({provider})",
|
||||
x_axis_label=f"Datetime [localtime {date_time_tz}]",
|
||||
@@ -157,7 +160,7 @@ def LoadForecast(predictions: pd.DataFrame, config: dict, date_time_tz: str, dar
|
||||
year_energy = config["load"]["loadakkudoktor"]["loadakkudoktor_year_energy_kwh"]
|
||||
provider = f"{provider}, {year_energy} kWh"
|
||||
|
||||
plot = figure(
|
||||
plot = create_figure(
|
||||
title=f"Load Prediction ({provider})",
|
||||
x_axis_type="datetime",
|
||||
x_axis_label=f"Datetime [localtime {date_time_tz}]",
|
||||
|
||||
@@ -35,6 +35,7 @@ from akkudoktoreos.core.coreabc import (
|
||||
get_resource_registry,
|
||||
singletons_init,
|
||||
)
|
||||
from akkudoktoreos.core.dataabc import DataImportMixin
|
||||
from akkudoktoreos.core.emplan import EnergyManagementPlan, ResourceStatus
|
||||
from akkudoktoreos.core.ems import ems_manage_energy
|
||||
from akkudoktoreos.core.emsettings import EnergyManagementMode
|
||||
@@ -88,7 +89,12 @@ from akkudoktoreos.server.server import (
|
||||
get_host_ip,
|
||||
wait_for_port_free,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration
|
||||
from akkudoktoreos.utils.datetimeutil import (
|
||||
DateTime,
|
||||
Duration,
|
||||
to_datetime,
|
||||
to_duration,
|
||||
)
|
||||
|
||||
# ----------------------
|
||||
# EOS REST Server
|
||||
@@ -671,6 +677,8 @@ async def fastapi_logging_get_log(
|
||||
"""
|
||||
log_path = get_config().logging.file_path
|
||||
try:
|
||||
if log_path is None:
|
||||
raise ValueError("Log file path is not configured")
|
||||
logs = read_file_log(
|
||||
log_path=log_path,
|
||||
limit=limit,
|
||||
@@ -864,16 +872,16 @@ async def fastapi_measurement_series_get(
|
||||
if processing == SeriesProcessing.RAW:
|
||||
pdseries = await get_measurement().key_to_raw_series(
|
||||
key=key,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
start_datetime=to_datetime(start_datetime) if start_datetime is not None else None,
|
||||
end_datetime=to_datetime(end_datetime) if end_datetime is not None else None,
|
||||
dropna=dropna,
|
||||
)
|
||||
else:
|
||||
pdseries = await get_measurement().key_to_series(
|
||||
key=key,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
interval=interval,
|
||||
start_datetime=to_datetime(start_datetime) if start_datetime is not None else None,
|
||||
end_datetime=to_datetime(end_datetime) if end_datetime is not None else None,
|
||||
interval=to_duration(interval) if interval is not None else None,
|
||||
fill_method=fill_method,
|
||||
resample_method=resample_method,
|
||||
dropna=dropna,
|
||||
@@ -1247,6 +1255,9 @@ async def fastapi_prediction_series_get(
|
||||
Returns:
|
||||
Array
|
||||
"""
|
||||
resolved_end_datetime: DateTime | None
|
||||
resolved_interval: Duration
|
||||
resolved_start_datetime: DateTime | None
|
||||
if key not in get_prediction().record_keys:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
@@ -1255,10 +1266,10 @@ async def fastapi_prediction_series_get(
|
||||
)
|
||||
|
||||
if start_datetime is None:
|
||||
start_datetime = get_prediction().ems_start_datetime
|
||||
resolved_start_datetime = get_prediction().ems_start_datetime
|
||||
else:
|
||||
try:
|
||||
start_datetime = to_datetime(start_datetime)
|
||||
resolved_start_datetime = to_datetime(start_datetime)
|
||||
except Exception as e:
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
@@ -1268,10 +1279,10 @@ async def fastapi_prediction_series_get(
|
||||
) from e
|
||||
|
||||
if end_datetime is None:
|
||||
end_datetime = get_prediction().end_datetime
|
||||
resolved_end_datetime = get_prediction().end_datetime
|
||||
else:
|
||||
try:
|
||||
end_datetime = to_datetime(end_datetime)
|
||||
resolved_end_datetime = to_datetime(end_datetime)
|
||||
except Exception as e:
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
@@ -1281,10 +1292,10 @@ async def fastapi_prediction_series_get(
|
||||
) from e
|
||||
|
||||
if interval is None:
|
||||
interval = to_duration("1 hour")
|
||||
resolved_interval = to_duration("1 hour")
|
||||
else:
|
||||
try:
|
||||
interval = to_duration(interval)
|
||||
resolved_interval = to_duration(interval)
|
||||
except Exception as e:
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
@@ -1297,16 +1308,16 @@ async def fastapi_prediction_series_get(
|
||||
if processing == SeriesProcessing.RAW:
|
||||
pdseries = await get_prediction().key_to_raw_series(
|
||||
key=key,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
start_datetime=resolved_start_datetime,
|
||||
end_datetime=resolved_end_datetime,
|
||||
dropna=dropna,
|
||||
)
|
||||
else:
|
||||
pdseries = await get_prediction().key_to_series(
|
||||
key=key,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
interval=interval,
|
||||
start_datetime=resolved_start_datetime,
|
||||
end_datetime=resolved_end_datetime,
|
||||
interval=resolved_interval,
|
||||
fill_method=fill_method,
|
||||
resample_method=resample_method,
|
||||
dropna=dropna,
|
||||
@@ -1417,24 +1428,26 @@ async def fastapi_prediction_dataframe_get(
|
||||
forecast or reporting queries where alignment to the exact query window is
|
||||
more important than clock-round boundaries.
|
||||
"""
|
||||
resolved_end_datetime: DateTime | None
|
||||
resolved_start_datetime: DateTime | None
|
||||
for key in keys:
|
||||
if key not in get_prediction().record_keys:
|
||||
raise HTTPException(status_code=404, detail=f"Key '{key}' is not available.")
|
||||
if start_datetime is None:
|
||||
start_datetime = get_prediction().ems_start_datetime
|
||||
resolved_start_datetime = get_prediction().ems_start_datetime
|
||||
else:
|
||||
start_datetime = to_datetime(start_datetime)
|
||||
resolved_start_datetime = to_datetime(start_datetime)
|
||||
if end_datetime is None:
|
||||
end_datetime = get_prediction().end_datetime
|
||||
resolved_end_datetime = get_prediction().end_datetime
|
||||
else:
|
||||
end_datetime = to_datetime(end_datetime)
|
||||
resolved_end_datetime = to_datetime(end_datetime)
|
||||
|
||||
try:
|
||||
prediction_df = await get_prediction().keys_to_dataframe(
|
||||
keys=keys,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
interval=interval,
|
||||
start_datetime=resolved_start_datetime,
|
||||
end_datetime=resolved_end_datetime,
|
||||
interval=to_duration(interval) if interval is not None else None,
|
||||
fill_method=fill_method,
|
||||
resample_method=resample_method,
|
||||
dropna=dropna,
|
||||
@@ -1536,6 +1549,9 @@ async def fastapi_prediction_list_get(
|
||||
forecast or reporting queries where alignment to the exact query window is
|
||||
more important than clock-round boundaries.
|
||||
"""
|
||||
resolved_end_datetime: DateTime | None
|
||||
resolved_interval: Duration
|
||||
resolved_start_datetime: DateTime | None
|
||||
if key not in get_prediction().record_keys:
|
||||
raise EOSProblem(
|
||||
status=404,
|
||||
@@ -1544,10 +1560,10 @@ async def fastapi_prediction_list_get(
|
||||
)
|
||||
|
||||
if start_datetime is None:
|
||||
start_datetime = get_prediction().ems_start_datetime
|
||||
resolved_start_datetime = get_prediction().ems_start_datetime
|
||||
else:
|
||||
try:
|
||||
start_datetime = to_datetime(start_datetime)
|
||||
resolved_start_datetime = to_datetime(start_datetime)
|
||||
except Exception as e:
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
@@ -1557,10 +1573,10 @@ async def fastapi_prediction_list_get(
|
||||
) from e
|
||||
|
||||
if end_datetime is None:
|
||||
end_datetime = get_prediction().end_datetime
|
||||
resolved_end_datetime = get_prediction().end_datetime
|
||||
else:
|
||||
try:
|
||||
end_datetime = to_datetime(end_datetime)
|
||||
resolved_end_datetime = to_datetime(end_datetime)
|
||||
except Exception as e:
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
@@ -1570,10 +1586,10 @@ async def fastapi_prediction_list_get(
|
||||
) from e
|
||||
|
||||
if interval is None:
|
||||
interval = to_duration("1 hour")
|
||||
resolved_interval = to_duration("1 hour")
|
||||
else:
|
||||
try:
|
||||
interval = to_duration(interval)
|
||||
resolved_interval = to_duration(interval)
|
||||
except Exception as e:
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
@@ -1585,9 +1601,9 @@ async def fastapi_prediction_list_get(
|
||||
try:
|
||||
prediction_array = await get_prediction().key_to_array(
|
||||
key=key,
|
||||
start_datetime=start_datetime,
|
||||
end_datetime=end_datetime,
|
||||
interval=interval,
|
||||
start_datetime=resolved_start_datetime,
|
||||
end_datetime=resolved_end_datetime,
|
||||
interval=resolved_interval,
|
||||
fill_method=fill_method,
|
||||
resample_method=resample_method,
|
||||
dropna=dropna,
|
||||
@@ -1655,6 +1671,12 @@ async def fastapi_prediction_import_provider(
|
||||
cause=e,
|
||||
) from e
|
||||
|
||||
if not isinstance(provider, DataImportMixin):
|
||||
raise EOSProblem(
|
||||
status=400,
|
||||
title="Prediction import failed",
|
||||
detail=f"Provider '{provider_id}' does not support data imports.",
|
||||
)
|
||||
await provider.import_from_json(json_str=json_str)
|
||||
provider.update_datetime = to_datetime(in_timezone=get_config().general.timezone)
|
||||
|
||||
@@ -2192,8 +2214,8 @@ async def fastapi_optimize(
|
||||
)
|
||||
|
||||
# Create compatible solution.
|
||||
legacy_solution = Genetic0SolutionLegacy(
|
||||
**{
|
||||
legacy_solution = Genetic0SolutionLegacy.model_validate(
|
||||
{
|
||||
"ac_charge": solution.ac_charge,
|
||||
"dc_charge": solution.dc_charge,
|
||||
"discharge_allowed": solution.discharge_allowed,
|
||||
@@ -2396,7 +2418,7 @@ def run_eos() -> None:
|
||||
port=config_eos.server.port,
|
||||
log_level=uv_log_level,
|
||||
access_log=True, # Fix server access logging to True
|
||||
reload=config_eos.server.reload,
|
||||
reload=bool(config_eos.server.reload),
|
||||
proxy_headers=True,
|
||||
forwarded_allow_ips="*",
|
||||
)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import html
|
||||
import traceback
|
||||
from dataclasses import dataclass
|
||||
from typing import cast
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import HTTPException, RequestValidationError
|
||||
@@ -54,7 +55,9 @@ def _problem_response(
|
||||
)
|
||||
|
||||
|
||||
async def eos_problem_handler(request: Request, exc: EOSProblem) -> JSONResponse:
|
||||
async def eos_problem_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
# Starlette dispatches this handler by the registered exception class.
|
||||
exc = cast(EOSProblem, exc)
|
||||
return _problem_response(
|
||||
request=request,
|
||||
status=exc.status,
|
||||
@@ -65,12 +68,14 @@ async def eos_problem_handler(request: Request, exc: EOSProblem) -> JSONResponse
|
||||
)
|
||||
|
||||
|
||||
async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
||||
async def http_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
# Starlette dispatches this handler by the registered exception class.
|
||||
http_exc = cast(HTTPException, exc)
|
||||
return _problem_response(
|
||||
request=request,
|
||||
status=exc.status_code,
|
||||
status=http_exc.status_code,
|
||||
title="HTTP Error",
|
||||
detail=str(exc.detail),
|
||||
detail=str(http_exc.detail),
|
||||
cause=exc,
|
||||
type="about:blank",
|
||||
)
|
||||
@@ -87,7 +92,9 @@ async def unexpected_exception_handler(request: Request, exc: Exception) -> JSON
|
||||
)
|
||||
|
||||
|
||||
async def validation_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
async def validation_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||
# Starlette dispatches this handler by the registered exception class.
|
||||
exc = cast(RequestValidationError, exc)
|
||||
return _problem_response(
|
||||
request=request,
|
||||
status=422,
|
||||
|
||||
@@ -4,10 +4,14 @@ import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, MutableMapping, Optional
|
||||
from typing import TYPE_CHECKING, Any, MutableMapping, Optional
|
||||
|
||||
from loguru import logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from loguru import Record
|
||||
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_config
|
||||
from akkudoktoreos.server.server import (
|
||||
validate_ip_or_hostname,
|
||||
@@ -99,7 +103,7 @@ def _emit_drop_warning() -> None:
|
||||
|
||||
|
||||
def patch_loguru_record(
|
||||
record: MutableMapping[str, Any],
|
||||
record: "Record | MutableMapping[str, Any]",
|
||||
*,
|
||||
file_name: str,
|
||||
file_path: str,
|
||||
|
||||
@@ -124,7 +124,12 @@ def wait_for_port_free(port: int, timeout: int = 0, waiting_app_name: str = "App
|
||||
|
||||
try:
|
||||
for conn in psutil.net_connections(kind="inet"):
|
||||
if conn.laddr.port == port and conn.pid not in seen_pids:
|
||||
if (
|
||||
conn.laddr
|
||||
and conn.laddr.port == port
|
||||
and conn.pid is not None
|
||||
and conn.pid not in seen_pids
|
||||
):
|
||||
try:
|
||||
process = psutil.Process(conn.pid)
|
||||
seen_pids.add(conn.pid)
|
||||
|
||||
Reference in New Issue
Block a user