enappsys 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
enappsys/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """
2
+ The EnAppSys Python client provides a light-weight client that allows for simple access
3
+ to EnAppSys' API services.
4
+ """
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ from .client import EnAppSys as EnAppSys
9
+ from .client_async import EnAppSysAsync as EnAppSysAsync
enappsys/client.py ADDED
@@ -0,0 +1,60 @@
1
+ from .services.bulk import BulkAPI
2
+ from .services.chart import ChartAPI
3
+ from .services.price_volume_curve import PriceVolumeCurveAPI
4
+ from .session import Session
5
+
6
+
7
+ class EnAppSys:
8
+ def __init__(
9
+ self,
10
+ user: str | None = None,
11
+ secret: str | None = None,
12
+ credentials_file: str | None = None,
13
+ max_retries: int = 3
14
+ ):
15
+ """
16
+ Client interface for the EnAppSys API.
17
+
18
+ Provides convenient access to the various service endpoints through dedicated
19
+ interfaces for bulk data retrieval, chart data, and price-volume curves.
20
+
21
+ This client handles authentication, request validation, chunked retrieval
22
+ for large datasets, automatic retries, and rate limiting.
23
+
24
+ Parameters
25
+ ----------
26
+ user : str | None, optional
27
+ EnAppSys username for authentication.
28
+ secret : str | None, optional
29
+ EnAppSys secret associated with the username.
30
+ credentials_file: str | None, optional
31
+ Path to a credentials file containing the user and secret.
32
+ Defaults to ``~/.credentials/enappsys.json``.
33
+ max_retries : int, default=3
34
+ Maximum number of retry attempts for failed HTTP requests.
35
+ """
36
+ self._session = Session(user, secret, credentials_file, max_retries)
37
+
38
+ # --- Public members ---
39
+ self.bulk = BulkAPI(self)
40
+ """An instance of :class:`BulkAPI`.
41
+
42
+ Provides access to the Bulk API for retrieving time series data,
43
+ such as generation, demand, and price data.
44
+ """
45
+
46
+ self.chart = ChartAPI(self)
47
+ """
48
+ An instance of :class:`ChartAPI`.
49
+
50
+ Provides access to the Chart API for retrieving time series data
51
+ from charts.
52
+ """
53
+
54
+ self.price_volume_curve = PriceVolumeCurveAPI(self)
55
+ """
56
+ An instance of :class:`PriceVolumeCurveAPI`.
57
+
58
+ Provides access to the Price Volume Curve API for retrieving
59
+ price volume curves from charts.
60
+ """
@@ -0,0 +1,65 @@
1
+ from typing import Literal, Union
2
+
3
+ from .enum import AppEnvEnum
4
+ from .services_async.bulk import AsyncBulkAPI
5
+ from .services_async.chart import AsyncChartAPI
6
+ from .services_async.price_volume_curve import AsyncPriceVolumeCurveAPI
7
+ from .session_async import AsyncSession
8
+
9
+
10
+ class EnAppSysAsync:
11
+ def __init__(
12
+ self,
13
+ user: str | None = None,
14
+ secret: str | None = None,
15
+ credentials_file: str | None = None,
16
+ max_retries: int = 3
17
+ ):
18
+ """Client for the EnAppSys API.
19
+
20
+ Parameters
21
+ ----------
22
+ user : str | None, optional
23
+ EnAppSys username.
24
+ secret : str | None, optional
25
+ EnAppSys secret.
26
+ credentials_file: str | None, optional
27
+ Specify path to the credentials file to have it at another place
28
+ than ~/.enappsys/api_credentials.json
29
+ profile_name : str | None, optional
30
+ Specify the profile name to load credentials from. If it is not found,
31
+ the ``default`` profile name will be used.
32
+ """
33
+ self._session = AsyncSession(
34
+ user, secret, credentials_file, max_retries
35
+ )
36
+
37
+ # --- Public members ---
38
+ self.bulk = AsyncBulkAPI(self)
39
+ """An instance of :class:`BulkAPI`.
40
+
41
+ Provides the interface for retrieving time series data.
42
+ """
43
+
44
+ self.chart = AsyncChartAPI(self)
45
+ """
46
+ An instance of :class:`ChartAPI`.
47
+
48
+ Provides the interface for retrieving data from a chart.
49
+ """
50
+
51
+ self.price_volume_curve = AsyncPriceVolumeCurveAPI(self)
52
+ """
53
+ An instance of :class:`PriceVolumeCurveAPI`.
54
+
55
+ Provides the interface for retrieving price volume curve data.
56
+ """
57
+
58
+ async def aclose(self) -> None:
59
+ await self._session.close()
60
+
61
+ async def __aenter__(self) -> "EnAppSysAsync":
62
+ return self
63
+
64
+ async def __aexit__(self, exc_type, exc, tb) -> None:
65
+ await self.aclose()
@@ -0,0 +1,101 @@
1
+ import json
2
+ import logging
3
+ import os
4
+
5
+ from pathlib import Path
6
+
7
+ from .exceptions import (
8
+ NoCredentialsError,
9
+ PartialCredentialsError,
10
+ InvalidCredentialsFile,
11
+ )
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class Credentials:
17
+ """Holds the credentials needed to authenticate requests."""
18
+
19
+ def __init__(
20
+ self,
21
+ user: str | None = None,
22
+ secret: str | None = None,
23
+ credentials_file: str | None = None
24
+ ) -> None:
25
+ """Initialize a :class:`Credentials` instance.
26
+
27
+ The EnAppSys client will look for credentials in the following order:
28
+ explicitly passed arguments, environment variables or a credentials file.
29
+
30
+ Parameters
31
+ ----------
32
+ user : str | None, optional
33
+ EnAppSys username.
34
+ secret : str | None, optional
35
+ EnAppSys secret.
36
+ credentials_file: str | None, optional
37
+ Specify path to the credentials file to have it at another place
38
+ than ~/.enappsys/api_credentials.json
39
+ """
40
+ self.user = user
41
+ self.secret = secret
42
+ self.credentials_file = credentials_file
43
+ self.method = None
44
+
45
+ if (
46
+ not self._set_with_explicit_args()
47
+ and not self._set_with_environment_vars()
48
+ and not self._set_with_config_file()
49
+ ):
50
+ raise NoCredentialsError()
51
+
52
+ self.api_format = {"user": self.user, "pass": self.secret}
53
+
54
+ def _set_with_explicit_args(self) -> bool:
55
+ self.method = "explicit arguments"
56
+
57
+ return self._validate_credentials()
58
+
59
+ def _set_with_environment_vars(self) -> bool:
60
+ self.method = "environment variables"
61
+
62
+ self.user = self.user or os.getenv("ENAPPSYS_USER")
63
+ self.secret = self.secret or os.getenv("ENAPPSYS_SECRET")
64
+
65
+ return self._validate_credentials()
66
+
67
+ def _set_with_config_file(self) -> bool:
68
+ self.method = "credentials file"
69
+
70
+ self.credentials_file = (
71
+ self.credentials_file or Path.home() / ".credentials" / "enappsys.json"
72
+ )
73
+
74
+ try:
75
+ with open(self.credentials_file, mode="r", encoding="utf-8") as f:
76
+ credentials = json.load(f)
77
+ except IOError as e:
78
+ raise InvalidCredentialsFile(
79
+ f"Could not retrieve credentials from '{self.credentials_file}'. "
80
+ f"Reason: {e}"
81
+ ) from e
82
+
83
+ self.user = credentials.get("user")
84
+ self.secret = credentials.get("secret")
85
+
86
+ if not self.user or not self.secret:
87
+ raise InvalidCredentialsFile(
88
+ f"Invalid format in credentials file '{self.credentials_file}'. "
89
+ f"Expected keys: 'user' and 'secret'. Got: {list(credentials.keys())}"
90
+ )
91
+
92
+ return self._validate_credentials()
93
+
94
+ def _validate_credentials(self) -> str | None:
95
+ if not self.user and not self.secret:
96
+ return False
97
+ elif self.user and not self.secret:
98
+ raise PartialCredentialsError(provider=self.method, cred_var="secret")
99
+ elif self.secret and not self.user:
100
+ raise PartialCredentialsError(provider=self.method, cred_var="user")
101
+ return True
enappsys/enum.py ADDED
@@ -0,0 +1,139 @@
1
+ from datetime import timedelta
2
+ from enum import Enum
3
+ from typing import Union
4
+
5
+ from .exceptions import ValidationError
6
+
7
+
8
+ class BaseEnum(Enum):
9
+ """Base Enum that resolves a member by matching any of its public attributes."""
10
+
11
+ @classmethod
12
+ def _from_value(cls, value: Union[str, int, float, bool, Enum, object]):
13
+ """Return the Enum member matching any of its public attribute values.
14
+
15
+ Accepts either:
16
+ - the Enum member itself
17
+ - any attribute value belonging to one of the Enum members
18
+ """
19
+ if isinstance(value, cls):
20
+ return value
21
+
22
+ # Iterate through all members and their public attributes
23
+ for member in cls:
24
+ for attr, attr_value in member.__dict__.items():
25
+ if attr.startswith("_"):
26
+ continue
27
+ if attr_value == value:
28
+ return member
29
+
30
+ # no match found → raise informative error
31
+ value_type = type(value).__name__
32
+ public_attrs = {
33
+ m.name: {k: v for k, v in m.__dict__.items() if not k.startswith("_")}
34
+ for m in cls
35
+ }
36
+ raise ValidationError(
37
+ reason=(
38
+ f"No match for {value!r} ({value_type}) in {cls.__name__}. "
39
+ f"Checked attributes:\n{public_attrs}"
40
+ )
41
+ )
42
+
43
+
44
+ class AppEnvEnum(BaseEnum):
45
+ APP = ("app", "https://app.enappsys.com")
46
+ APPQA = ("appqa", "https://appqa.enappsys.com")
47
+ APPDEV = ("appdev", "https://appdev.enappsys.com")
48
+
49
+ def __init__(self, platform, app_env_url):
50
+ self.platform = platform
51
+ self.app_env_url = app_env_url
52
+
53
+
54
+ class ResponseFormatEnum(BaseEnum):
55
+ JSON = ("json", "jsonapi", "json", "JSON")
56
+ JSON_MAP = ("json_map", "jsonmapapi", "json_map", None)
57
+ CSV = ("csv", "csvapi", "csv", "CSV")
58
+ XML = ("xml", "xmlapi", "xml", "XML")
59
+
60
+ def __init__(self, platform, bulk_url, chart_tag, epex_tag):
61
+ self.platform = platform
62
+ self.bulk_url = bulk_url
63
+ self.chart_tag = chart_tag
64
+ self.epex_tag = epex_tag
65
+
66
+
67
+ class ResolutionEnum(BaseEnum):
68
+ """Supported temporal resolutions with platform, ISO 8601, pandas and timedelta."""
69
+
70
+ PT1S = ("1s", "PT1S", "s", timedelta(seconds=1))
71
+ PT15S = ("15s", "PT15S", "15s", timedelta(seconds=15))
72
+ PT1M = ("min", "PT1M", "min", timedelta(minutes=1))
73
+ PT5M = ("5min", "PT5M", "5min", timedelta(minutes=5))
74
+ PT15M = ("qh", "PT15M", "15min", timedelta(minutes=15))
75
+ PT30M = ("hh", "PT30M", "30min", timedelta(minutes=30))
76
+ PT1H = ("hourly", "PT1H", "h", timedelta(hours=1))
77
+ PT3H = ("3hourly", "PT3H", "3h", timedelta(hours=3))
78
+ PT6H = ("6hourly", "PT6H", "6h", timedelta(hours=6))
79
+ PT12H = ("12hourly", "PT12H", "12h", timedelta(hours=12))
80
+ P1D = ("daily", "P1D", "D", timedelta(days=1))
81
+ P1W = ("weekly", "P1W", "W", timedelta(weeks=1))
82
+ P1M = ("monthly", "P1M", "M", timedelta(days=30))
83
+ P1Y = ("yearly", "P1Y", "Y", timedelta(days=365))
84
+
85
+ def __init__(self, platform: str, iso: str, pandas: str, delta: timedelta):
86
+ self.platform = platform
87
+ self.iso = iso
88
+ self.pandas = pandas
89
+ self.delta = delta
90
+
91
+
92
+ class TimeZoneEnum(BaseEnum):
93
+ UTC = "UTC"
94
+ WET = "WET"
95
+ CET = "CET"
96
+ EET = "EET"
97
+
98
+ def __init__(self, platform):
99
+ self.platform = platform
100
+
101
+
102
+ class CurrencyEnum(BaseEnum):
103
+ BAM = "BAM"
104
+ BGN = "BGN"
105
+ CAD = "CAD"
106
+ CHF = "CHF"
107
+ CNY = "CNY"
108
+ CZK = "CZK"
109
+ DKK = "DKK"
110
+ EUR = "EUR"
111
+ EURCENTS = "EURcents"
112
+ GBP = "GBP"
113
+ GBPPENCE = "GBPpence"
114
+ HKD = "HKD"
115
+ HRK = "HRK"
116
+ HUF = "HUF"
117
+ JPY = "JPY"
118
+ NOK = "NOK"
119
+ PLN = "PLN"
120
+ RON = "RON"
121
+ RUB = "RUB"
122
+ SEK = "SEK"
123
+ SGD = "SGD"
124
+ TRY = "TRY"
125
+ USD = "USD"
126
+
127
+ def __init__(self, platform):
128
+ self.platform = platform
129
+
130
+
131
+ class DelimiterEnum(BaseEnum):
132
+ COMMA = ("comma", ",")
133
+ TAB = ("tab", "")
134
+ SEMICOLON = ("semicolon", ";")
135
+ PIPE = ("pipe", "|")
136
+
137
+ def __init__(self, platform, character):
138
+ self.platform = platform
139
+ self.character = character
enappsys/exceptions.py ADDED
@@ -0,0 +1,113 @@
1
+ """EnAppSys exception classes.
2
+
3
+ Includes two main exceptions: :class:`.APIError` for when something goes
4
+ wrong on the server side, and :class:`.ClientError` for when something goes wrong
5
+ on the client side. Both of these classes extend :class:`.EnAppSysException`.
6
+ """
7
+
8
+
9
+ class EnAppSysException(Exception):
10
+ """The base Exception that all other exception classes extend."""
11
+
12
+ def __init__(self, *args, **kwargs):
13
+ super().__init__(*args, **kwargs)
14
+
15
+
16
+ class ClientError(EnAppSysException):
17
+ """
18
+ Base exception for all errors that may occur in this client.
19
+ """
20
+
21
+ def __init__(self, *args, **kwargs):
22
+ super().__init__(*args, **kwargs)
23
+
24
+
25
+ class APIError(EnAppSysException):
26
+ """
27
+ Base exception for all errors that may occur during an API call.
28
+ """
29
+
30
+ def __init__(self, *args, **kwargs):
31
+ super().__init__(*args, **kwargs)
32
+
33
+
34
+ class ValidationError(APIError):
35
+ """
36
+ Validation error of some kind (invalid parameter or combination
37
+ of parameters).
38
+ """
39
+
40
+ def __init__(self, reason=None, parameter=None, *args, **kwargs):
41
+ super().__init__(*args, **kwargs)
42
+ self.reason = reason
43
+ self.parameter = parameter
44
+
45
+ def __str__(self):
46
+ if self.parameter:
47
+ return f'Field="{self.parameter}", message: {self.reason}'
48
+ else:
49
+ return self.reason
50
+
51
+
52
+ class HTTPError(APIError):
53
+ """
54
+ Base class for all HTTP errors. Mostly used to wrap request's HTTP errors.
55
+ """
56
+
57
+ def __init__(self, *args, **kwargs):
58
+ super().__init__(*args, **kwargs)
59
+
60
+
61
+ class BadRequest(APIError):
62
+ """Malformed request parameters."""
63
+
64
+ def __init__(self, *args, **kwargs):
65
+ super().__init__(*args, **kwargs)
66
+
67
+
68
+ class ContentTooLarge(APIError):
69
+ """Request exceeds defined limits."""
70
+
71
+ def __init__(self, *args, **kwargs):
72
+ super().__init__(*args, **kwargs)
73
+
74
+
75
+ class InternalServerError(APIError):
76
+ """Other type of errors."""
77
+
78
+ def __init__(self, msg):
79
+ super().__init__(f"Data type might be incorrect, original message: \n\n{msg}.")
80
+
81
+
82
+ class NoCredentialsError(ClientError):
83
+ """No credentials were found."""
84
+
85
+ def __init__(self):
86
+ super().__init__(
87
+ "No credentials were found, either pass them to the client"
88
+ " explicitly, through environment variables or by specifying"
89
+ " them in a credentials JSON file."
90
+ )
91
+
92
+
93
+ class PartialCredentialsError(ClientError):
94
+ """Only partial credentials were found."""
95
+
96
+ def __init__(self, provider, cred_var):
97
+ super().__init__(
98
+ f"Partial credentials found in {provider}, missing: {cred_var}"
99
+ )
100
+
101
+
102
+ class InvalidCredentials(ClientError):
103
+ """Username and/or password invalid."""
104
+
105
+ def __init__(self):
106
+ super().__init__("Username and/or password are invalid.")
107
+
108
+
109
+ class InvalidCredentialsFile(ClientError):
110
+ """Malformed credentials file"""
111
+
112
+ def __init__(self, *args, **kwargs):
113
+ super().__init__(*args, **kwargs)
File without changes