pystromligning 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pystromligning
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Library for communicating with the Stromligning API
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -37,3 +37,26 @@ Use `set_electricity_price(None)` to clear the saved price.
37
37
 
38
38
  API documentation: https://stromligning.dk/api/docs/
39
39
 
40
+ ## Production prices
41
+
42
+ `update_production(start)` fetches sale prices for surplus production (for
43
+ example solar) from `/prices/production` for the grid supplier found by
44
+ `set_location()`, and stores them in `production_prices`. It uses the same
45
+ aggregation and forecast settings as `update()`. Each price is the spot price
46
+ excluding VAT, less Energinet's and the grid supplier's production tariffs; the
47
+ tariff deductions and their VAT are negative values.
48
+
49
+ ## User-Agent and API key
50
+
51
+ `Stromligning(dev=False, api_key=None, user_agent=None)`:
52
+
53
+ - `user_agent` identifies your application, for example `"MyApp/1.0"`. The
54
+ library appends its own name and version, so requests are sent with
55
+ `User-Agent: MyApp/1.0 pystromligning/<version>`. Without it the User-Agent is
56
+ `pystromligning/<version>`.
57
+ - `api_key` is optional and sent as `Authorization: Bearer <key>`. Create a key
58
+ at https://stromligning.dk/bruger/api-noegler. Requests with a key are rate
59
+ limited per key instead of per IP address. Use `set_api_key(None)` to clear it.
60
+ A rejected key (HTTP 401) raises `InvalidAPIKey`, a subclass of
61
+ `InvalidAPIResponse`. The key is never logged.
62
+
@@ -0,0 +1,42 @@
1
+ ![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)
2
+
3
+ ## pyStromligning
4
+
5
+ This is a PyPI module for communicating with the Stromligning API, primarily developed for use with [Home Assistant](https://home-assistant.io), but I try to keep it as widely usable as possible.
6
+ ## Fixed-price products
7
+
8
+ `available_companies` includes each product's `productType` (`fixed` or `variable`).
9
+ For fixed-price products, call `set_electricity_price(price)` with the customer's
10
+ agreed electricity price in kr/kWh **excluding VAT** before `update()`. The price
11
+ is sent as the documented `electricityPrice` parameter. Zero is supported;
12
+ negative, non-finite and non-numeric values are rejected. A missing price raises
13
+ `FixedPriceRequired` before a network request is made.
14
+
15
+ The catalogue's current `fixedPrice` is not used as the customer's agreed price.
16
+ Variable products omit `electricityPrice`, even if a price was previously set.
17
+ Use `set_electricity_price(None)` to clear the saved price.
18
+
19
+ API documentation: https://stromligning.dk/api/docs/
20
+
21
+ ## Production prices
22
+
23
+ `update_production(start)` fetches sale prices for surplus production (for
24
+ example solar) from `/prices/production` for the grid supplier found by
25
+ `set_location()`, and stores them in `production_prices`. It uses the same
26
+ aggregation and forecast settings as `update()`. Each price is the spot price
27
+ excluding VAT, less Energinet's and the grid supplier's production tariffs; the
28
+ tariff deductions and their VAT are negative values.
29
+
30
+ ## User-Agent and API key
31
+
32
+ `Stromligning(dev=False, api_key=None, user_agent=None)`:
33
+
34
+ - `user_agent` identifies your application, for example `"MyApp/1.0"`. The
35
+ library appends its own name and version, so requests are sent with
36
+ `User-Agent: MyApp/1.0 pystromligning/<version>`. Without it the User-Agent is
37
+ `pystromligning/<version>`.
38
+ - `api_key` is optional and sent as `Authorization: Bearer <key>`. Create a key
39
+ at https://stromligning.dk/bruger/api-noegler. Requests with a key are rate
40
+ limited per key instead of per IP address. Use `set_api_key(None)` to clear it.
41
+ A rejected key (HTTP 401) raises `InvalidAPIKey`, a subclass of
42
+ `InvalidAPIResponse`. The key is never logged.
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "pystromligning"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Library for communicating with the Stromligning API"
5
5
  authors = ["Malene Trab <malene@trab.dk>"]
6
6
  license = "MIT"
@@ -6,18 +6,39 @@ import logging
6
6
  import math
7
7
  import sys
8
8
  from datetime import datetime, timezone
9
+ from importlib.metadata import PackageNotFoundError, version
9
10
  from operator import itemgetter
10
11
 
11
12
  import requests
12
13
 
13
14
  from .const import API_URL, DEV_API_URL
14
- from .exceptions import FixedPriceRequired, InvalidAPIResponse, TooManyRequests
15
+ from .exceptions import (
16
+ FixedPriceRequired,
17
+ InvalidAPIKey,
18
+ InvalidAPIResponse,
19
+ TooManyRequests,
20
+ )
15
21
 
16
22
  if sys.version_info < (3, 11, 0):
17
23
  sys.exit("The pyWorxcloud module requires Python 3.11.0 or later")
18
24
 
19
25
  _LOGGER = logging.getLogger(__name__)
20
26
 
27
+ try:
28
+ LIBRARY_USER_AGENT = f"pystromligning/{version('pystromligning')}"
29
+ except PackageNotFoundError:
30
+ LIBRARY_USER_AGENT = "pystromligning"
31
+
32
+
33
+ def _midnight_utc() -> str:
34
+ """Return local midnight today as a UTC timestamp for the API."""
35
+ return (
36
+ datetime.now()
37
+ .replace(hour=0, minute=0, second=0, microsecond=0)
38
+ .astimezone(timezone.utc)
39
+ .isoformat()
40
+ ).replace("+00:00", ".000Z")
41
+
21
42
 
22
43
  class Aggregation(str):
23
44
  """Strømligning aggregation levels."""
@@ -44,8 +65,18 @@ class Stromligning:
44
65
  Results are electricity prices that takes into account the tariffs and other fees.
45
66
  """
46
67
 
47
- def __init__(self, dev: bool = False) -> None:
48
- """Initialize the :class:Stromligning class and set default attribute values."""
68
+ def __init__(
69
+ self,
70
+ dev: bool = False,
71
+ api_key: str | None = None,
72
+ user_agent: str | None = None,
73
+ ) -> None:
74
+ """Initialize the :class:Stromligning class and set default attribute values.
75
+
76
+ ``user_agent`` identifies the calling application, for example
77
+ ``"MyApp/1.0"``; the library's own name and version are appended.
78
+ ``api_key`` is sent as a bearer token when set.
79
+ """
49
80
  _LOGGER.debug("Initializing the pyStromligning library")
50
81
  self._location: dict = {}
51
82
 
@@ -53,12 +84,31 @@ class Stromligning:
53
84
  self.available_companies: list = []
54
85
 
55
86
  self.prices: list = []
87
+ self.production_prices: list = []
56
88
  self.company: dict = {}
57
89
  self.aggregation: str = Aggregation.HOUR
58
90
  self.forecast: bool = False
59
91
  self.electricity_price: float | None = None
60
92
 
61
93
  self.dev_api: bool = dev
94
+ self._api_key: str | None = None
95
+ self.set_api_key(api_key)
96
+ self.user_agent: str = (
97
+ f"{user_agent} {LIBRARY_USER_AGENT}" if user_agent else LIBRARY_USER_AGENT
98
+ )
99
+
100
+ def set_api_key(self, api_key: str | None) -> None:
101
+ """Set or clear the API key. Empty or blank keys are treated as no key."""
102
+ if api_key is not None and not isinstance(api_key, str):
103
+ raise TypeError("API key must be a string")
104
+ self._api_key = api_key.strip() if api_key and api_key.strip() else None
105
+
106
+ def _headers(self) -> dict:
107
+ """Return request headers; the API key is never logged."""
108
+ headers = {"User-Agent": self.user_agent}
109
+ if self._api_key:
110
+ headers["Authorization"] = f"Bearer {self._api_key}"
111
+ return headers
62
112
 
63
113
  def set_forecast(self, forecast: bool) -> None:
64
114
  """Set if forecast prices should be used."""
@@ -123,12 +173,7 @@ class Stromligning:
123
173
  def update(self, start: str | None = None) -> None:
124
174
  """Get current available prices."""
125
175
  if start is None:
126
- start = (
127
- datetime.now()
128
- .replace(hour=0, minute=0, second=0, microsecond=0)
129
- .astimezone(timezone.utc)
130
- .isoformat()
131
- ).replace("+00:00", ".000Z")
176
+ start = _midnight_utc()
132
177
 
133
178
  aggregation = ""
134
179
  if self.aggregation != Aggregation.MIN15:
@@ -163,21 +208,51 @@ class Stromligning:
163
208
 
164
209
  self.prices = price_list
165
210
 
211
+ def update_production(self, start: str | None = None) -> None:
212
+ """Get sale prices for surplus production at the selected grid supplier.
213
+
214
+ Prices are spot prices excluding VAT, less the production tariffs from
215
+ Energinet and the grid supplier. Tariff deductions are negative values.
216
+ """
217
+ if start is None:
218
+ start = _midnight_utc()
219
+
220
+ aggregation = ""
221
+ if self.aggregation != Aggregation.MIN15:
222
+ aggregation = "&aggregation=" + self.aggregation
223
+
224
+ url = (
225
+ f"/prices/production?supplierId={self.supplier['id']}"
226
+ f"&from={start}{aggregation}"
227
+ f"&forecast={str(self.forecast).lower()}"
228
+ )
229
+
230
+ _LOGGER.debug("Fetching production prices")
231
+
232
+ price_list: list = []
233
+ for price in sorted(
234
+ (self._get_response(url))["prices"],
235
+ key=itemgetter("date"),
236
+ ):
237
+ if price not in price_list:
238
+ price_list.append(price)
239
+
240
+ self.production_prices = price_list
241
+
166
242
  def _get_response(self, path: str) -> dict:
167
243
  """Make the request to the API."""
168
244
 
169
- if not self.dev_api:
170
- response = requests.get(
171
- f"{API_URL}{path}",
172
- timeout=60,
173
- )
174
- else:
175
- response = requests.get(
176
- f"{DEV_API_URL}{path}",
177
- timeout=60,
178
- )
245
+ response = requests.get(
246
+ f"{DEV_API_URL if self.dev_api else API_URL}{path}",
247
+ headers=self._headers(),
248
+ timeout=60,
249
+ )
179
250
 
180
251
  if response.status_code != 200:
252
+ if response.status_code == 401:
253
+ raise InvalidAPIKey(
254
+ "The API key was rejected (invalid, deactivated or expired)"
255
+ )
181
256
  if response.status_code == 429:
182
257
  raise TooManyRequests(
183
258
  "Too many requests from this IP, please try again after 15 minutes"
@@ -5,6 +5,10 @@ class InvalidAPIResponse(Exception):
5
5
  """Invalid response received from the API."""
6
6
 
7
7
 
8
+ class InvalidAPIKey(InvalidAPIResponse):
9
+ """The API key was rejected because it is invalid, deactivated or expired."""
10
+
11
+
8
12
  class TooManyRequests(Exception):
9
13
  """Too many requests, try again in 15 minutes."""
10
14
 
@@ -1,19 +0,0 @@
1
- ![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)
2
-
3
- ## pyStromligning
4
-
5
- This is a PyPI module for communicating with the Stromligning API, primarily developed for use with [Home Assistant](https://home-assistant.io), but I try to keep it as widely usable as possible.
6
- ## Fixed-price products
7
-
8
- `available_companies` includes each product's `productType` (`fixed` or `variable`).
9
- For fixed-price products, call `set_electricity_price(price)` with the customer's
10
- agreed electricity price in kr/kWh **excluding VAT** before `update()`. The price
11
- is sent as the documented `electricityPrice` parameter. Zero is supported;
12
- negative, non-finite and non-numeric values are rejected. A missing price raises
13
- `FixedPriceRequired` before a network request is made.
14
-
15
- The catalogue's current `fixedPrice` is not used as the customer's agreed price.
16
- Variable products omit `electricityPrice`, even if a price was previously set.
17
- Use `set_electricity_price(None)` to clear the saved price.
18
-
19
- API documentation: https://stromligning.dk/api/docs/
File without changes