pyrapion 0.1.0__py2.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.
pyrapion/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Top-level package for Python Package for Restful API Interaction."""
2
+
3
+ __author__ = """Long Lê"""
4
+ __email__ = 'long.le-van@outlook.com'
5
+ __version__ = '0.1.0'
pyrapion/cli.py ADDED
@@ -0,0 +1,19 @@
1
+ """Console script for pyrapion."""
2
+ import argparse
3
+ import sys
4
+
5
+
6
+ def main():
7
+ """Console script for pyrapion."""
8
+ parser = argparse.ArgumentParser()
9
+ parser.add_argument('_', nargs='*')
10
+ args = parser.parse_args()
11
+
12
+ print("Arguments: " + str(args._))
13
+ print("Replace this message by putting your code into "
14
+ "pyrapion.cli.main")
15
+ return 0
16
+
17
+
18
+ if __name__ == "__main__":
19
+ sys.exit(main()) # pragma: no cover
@@ -0,0 +1,841 @@
1
+ """
2
+ This module provides an ApiClient class and utility functions for
3
+ interacting with the Energis Cloud API, including asset management,
4
+ metric queries, and data retrieval for energy-related assets.
5
+ """
6
+
7
+ import datetime as dt
8
+ import sys
9
+
10
+ import pandas as pd
11
+ import pytz
12
+ import requests
13
+ from loguru import logger
14
+
15
+
16
+ def split_list(lst, chunk_size):
17
+ return [lst[i: i + chunk_size] for i in range(0, len(lst), chunk_size)]
18
+
19
+
20
+ def toDateTimeIsoFormatString(
21
+ dt_value,
22
+ dt_tz=pytz.timezone("Europe/Brussels")
23
+ ):
24
+
25
+ if isinstance(dt_value, dt.datetime):
26
+ pass
27
+ elif isinstance(dt_value, dt.date):
28
+ logger.warning("the datetime value is a date instance")
29
+ else:
30
+ logger.error(
31
+ f"datetime value must be a datetime instance not {type(dt_value)}"
32
+ )
33
+ sys.exit(1)
34
+
35
+ if dt_value.tzinfo is None or dt_value.tzinfo.utcoffset(dt_value) is None:
36
+ dt_value_local = dt_tz.localize(dt_value)
37
+ dt_value_utc = dt_value_local.astimezone(pytz.utc)
38
+ dt_value_naive = dt_value_utc.replace(tzinfo=None)
39
+ else:
40
+ dt_value_utc = dt_value.astimezone(pytz.utc)
41
+ dt_value_naive = dt_value_utc.replace(tzinfo=None)
42
+
43
+ dateTimeIsoFormat = "%Y-%m-%dT%H:%M:%SZ"
44
+ return dt.datetime.strftime(dt_value_naive, dateTimeIsoFormat)
45
+
46
+
47
+ class ApiClient:
48
+ def __init__(self, api_key, env_url=None) -> None:
49
+ self.env_url = env_url
50
+ self.api_key = api_key
51
+ self.headers = {"X-Api-Key": api_key}
52
+ if self.env_url and not self.env_url[-1] == "/":
53
+ raise Exception(
54
+ "The environment url must be ended with a forward slash"
55
+ )
56
+ if not self.env_url:
57
+ raise Exception(
58
+ "The env_url is missing, please provide the env_url"
59
+ )
60
+
61
+ # def get_site_asset_list_by_assetId(self,api_url, siteID):
62
+ # if api_url.startswith("/"):
63
+ # print("api url should no start with a forward slash")
64
+ # url = self.env_url + api_url
65
+ # r_entity = requests.get(
66
+ # url + f"{siteID}",
67
+ # headers=self.headers,
68
+ # verify=False
69
+ # ).json()
70
+ # return r_entity
71
+ # =============== General POST Request ============
72
+ def post_request(self, api_url, message):
73
+ """
74
+ api_url: str
75
+ api url
76
+ message: dict
77
+ message to be sent to the server
78
+ """
79
+ url = self.env_url + api_url
80
+ r_entity = requests.post(
81
+ url,
82
+ headers=self.headers,
83
+ json=message,
84
+ verify=False
85
+ )
86
+ return r_entity
87
+
88
+ # =============== General GET Request ========
89
+ def get_request(self, api_url, message):
90
+ """
91
+ api_url: str
92
+ api url
93
+ message: dict
94
+ message to be sent to the server
95
+ """
96
+ url = self.env_url + api_url
97
+ r_entity = requests.get(
98
+ url,
99
+ headers=self.headers,
100
+ json=message,
101
+ verify=False
102
+ )
103
+ return r_entity
104
+
105
+ # ======================= DATASOURCE =======================
106
+ def get_datasource_list(self):
107
+
108
+ api_url = "api/mw/v1/datasource"
109
+ url = self.env_url + api_url
110
+ r_ds = requests.get(url, headers=self.headers, verify=False)
111
+ return r_ds
112
+
113
+ def get_datasource_by_ID(self, dsID: int):
114
+ """
115
+ dsID: str or int
116
+ datasource ID
117
+ """
118
+ api_url = f"api/mw/v1/datasource/{dsID}"
119
+
120
+ url = self.env_url + api_url
121
+ r_ds = requests.get(url, headers=self.headers, verify=False)
122
+
123
+ return r_ds
124
+
125
+ def get_datasourceMetrics_by_datasourceId(self, dsID: int):
126
+
127
+ r_ds = self.get_datasource_by_ID(dsID)
128
+ datasourceMetrics = r_ds.json()["datasourceMetrics"]
129
+ return datasourceMetrics
130
+
131
+ # ===================== METRIC ============================
132
+ def create_or_update_semistatic_metric(
133
+ self,
134
+ assetCode: str,
135
+ externalName: str,
136
+ metricValue: float,
137
+ startDate,
138
+ endDate
139
+ ):
140
+ api_url = "api/mw/v1/metric/semi-static-update"
141
+ url = self.env_url + api_url
142
+
143
+ if not (
144
+ isinstance(startDate, dt.datetime) or isinstance(endDate, dt.date)
145
+ ):
146
+ logger.error(
147
+ "startDate must be datetime or "
148
+ f"date instance not {type(startDate)}"
149
+ )
150
+ return 1
151
+ if not (
152
+ isinstance(endDate, dt.datetime) or isinstance(endDate, dt.date)
153
+ ):
154
+ logger.error(
155
+ "endDate must be a datetime or "
156
+ f"date instance not {type(endDate)}"
157
+ )
158
+ return 1
159
+ endDateString = toDateTimeIsoFormatString(endDate)
160
+ startDateString = toDateTimeIsoFormatString(startDate)
161
+ message = {
162
+ "assetCode": assetCode,
163
+ "endDate": endDateString,
164
+ "externalName": externalName,
165
+ "startDate": startDateString,
166
+ "value": metricValue,
167
+ }
168
+ res = requests.post(
169
+ url,
170
+ headers=self.headers,
171
+ json=message,
172
+ verify=False
173
+ )
174
+ # r_data=res.json()
175
+ return res
176
+
177
+ def get_the_label_list_given_an_id(self, labelID):
178
+ api_url = f"api/mw/v1/labels/id/{labelID}"
179
+ url = self.env_url + api_url
180
+
181
+ r_label = requests.get(url, headers=self.headers, verify=False)
182
+ return r_label
183
+
184
+ def update_site_asset(
185
+ self,
186
+ entityID,
187
+ assetCode=None,
188
+ assetName=None,
189
+ parentID=None,
190
+ companyAssetId=2665,
191
+ **kwargs,
192
+ ):
193
+ api_url = f"api/mw/v1/site/{entityID}"
194
+ url = self.env_url + api_url
195
+
196
+ message = self.get_site_by_ID(entityID)
197
+ category = kwargs.get("category", None)
198
+
199
+ if parentID:
200
+ message["parentId"] = parentID
201
+ if assetName:
202
+ message["name"] = assetName
203
+ if assetCode:
204
+ message["code"] = assetCode
205
+ if category:
206
+ message["category"] = category
207
+
208
+ r_entity = requests.put(
209
+ url,
210
+ headers=self.headers,
211
+ json=message,
212
+ verify=False
213
+ )
214
+ return r_entity
215
+
216
+ def update_site_entity_asset(
217
+ self,
218
+ entityID,
219
+ assetCode=None,
220
+ assetName=None,
221
+ parentID=None,
222
+ description="",
223
+ companyAssetId=2665,
224
+ **kwargs,
225
+ ):
226
+ api_url = f"api/mw/v1/site-entity/{entityID}"
227
+ url = self.env_url + api_url
228
+
229
+ message = self.get_site_entity_by_ID(entityID)
230
+ energyType = kwargs.get("energyType", None)
231
+ category = kwargs.get("category", None)
232
+ categoryId = kwargs.get("categoryId", None)
233
+
234
+ if parentID:
235
+ message["parentId"] = parentID
236
+ if description:
237
+ message["description"] = description
238
+ if assetName:
239
+ message["name"] = assetName
240
+ if assetCode:
241
+ message["code"] = assetCode
242
+ if energyType:
243
+ message["energyType"] = energyType
244
+ if category:
245
+ message["category"] = category
246
+ if categoryId:
247
+ message["categoryId"] = categoryId
248
+
249
+ # if tags:
250
+ # tag_list = []
251
+ # for tag in tags:
252
+ # tag_instance = self.get_the_label_list_given_an_id(
253
+ # tag["id"]
254
+ # ).json()
255
+ # if not tag_list:
256
+ # tag_list = tag_instance
257
+ # else:
258
+ # tag_list = tag_list + tag_instance
259
+ # if tag_list:
260
+ # message["tags"] = tag_list
261
+ # print(tag_list)
262
+
263
+ r_entity = requests.put(
264
+ url,
265
+ headers=self.headers,
266
+ json=message,
267
+ verify=False
268
+ )
269
+ return r_entity
270
+
271
+ def link_tags_to_assets(
272
+ self,
273
+ companyAssetId=2665,
274
+ asset_ids=[],
275
+ link_on_tagids=[],
276
+ link_off_tagids=[]
277
+ ):
278
+ api_url = f"api/v1/asset-tags/apply?{companyAssetId}"
279
+ url = self.env_url + api_url
280
+
281
+ message = {
282
+ "assetIds": asset_ids,
283
+ "linkOnTagIds": link_on_tagids,
284
+ "linkOffTagIds": link_off_tagids,
285
+ "newTags": None,
286
+ }
287
+ r_linkTags = requests.post(
288
+ # f"https://equans.energis.cloud/energiscloud-gateway/restful/api/v1/asset-tags/apply?{companyAssetId}",
289
+ url,
290
+ headers=self.headers,
291
+ json=message,
292
+ verify=False,
293
+ )
294
+ return r_linkTags
295
+
296
+ def create_site_asset(
297
+ self,
298
+ assetCode,
299
+ assetName,
300
+ parentID,
301
+ description="",
302
+ companyAssetId=2665,
303
+ **kwargs,
304
+ ):
305
+ api_url = "api/mw/v1/site"
306
+ url = self.env_url + api_url
307
+
308
+ category = kwargs.get("category", "OFFICE")
309
+ message = {
310
+ "companyAssetId": companyAssetId,
311
+ "code": assetCode,
312
+ "name": assetName,
313
+ "description": description,
314
+ "type": "SITE",
315
+ "categoryId": None,
316
+ "category": category,
317
+ "parentId": parentID,
318
+ }
319
+
320
+ if description:
321
+ message["description"] = description
322
+
323
+ for k, v in kwargs.items():
324
+ if k not in message.keys():
325
+ message[k] = v
326
+
327
+ r_entity = requests.post(
328
+ url,
329
+ headers=self.headers,
330
+ json=message,
331
+ verify=False
332
+ )
333
+ return r_entity
334
+
335
+ def create_site_entity_asset(
336
+ self,
337
+ assetCode,
338
+ assetName,
339
+ parentID,
340
+ description="",
341
+ companyAssetId=2665,
342
+ **kwargs,
343
+ ):
344
+ api_url = "api/mw/v1/site-entity"
345
+ url = self.env_url + api_url
346
+
347
+ message = {
348
+ "companyAssetId": companyAssetId,
349
+ "code": assetCode,
350
+ "name": assetName,
351
+ "type": "SITE_ENTITY",
352
+ "parentId": parentID,
353
+ }
354
+ if description:
355
+ message["description"] = description
356
+ for k, v in kwargs.items():
357
+ if k not in message.keys():
358
+ message[k] = v
359
+
360
+ r_entity = requests.post(
361
+ url,
362
+ headers=self.headers,
363
+ json=message,
364
+ verify=False
365
+ )
366
+ return r_entity
367
+
368
+ def copy_energis_asset(
369
+ self,
370
+ org_asset_id,
371
+ copyAssetParentId,
372
+ copyAssetCode=None,
373
+ copyAssetName=None,
374
+ metricClonning=False,
375
+ metricSplitGroups=2,
376
+ **kwargs,
377
+ ):
378
+ # get asset detail from id
379
+ orgAssetDetail = self.get_asset_detail_from_id(org_asset_id)
380
+ # NOTE: should add try except for handling error
381
+ if not copyAssetCode:
382
+ copyAssetCode = orgAssetDetail["code"] + "-Copy"
383
+ if not copyAssetName:
384
+ copyAssetName = orgAssetDetail["name"] + "-Copy"
385
+
386
+ if orgAssetDetail["type"] == "SITE":
387
+ siteAssetDetail = self.get_site_by_ID(org_asset_id)
388
+ assetCreation = self.create_site_asset(
389
+ copyAssetCode,
390
+ copyAssetName,
391
+ copyAssetParentId,
392
+ category=siteAssetDetail["category"],
393
+ description=siteAssetDetail["description"],
394
+ box=siteAssetDetail["box"],
395
+ city=siteAssetDetail["city"],
396
+ postalCode=siteAssetDetail["postalCode"],
397
+ street=siteAssetDetail["street"],
398
+ streetNumber=siteAssetDetail["streetNumber"],
399
+ countryCode=siteAssetDetail["countryCode"],
400
+ latitude=siteAssetDetail["latitude"],
401
+ longitude=siteAssetDetail["longitude"],
402
+ notes=siteAssetDetail["notes"],
403
+ regionCode=siteAssetDetail["regionCode"],
404
+ )
405
+ if assetCreation.status_code != 200:
406
+ logger.error(
407
+ "Error on asset creattion {}: {}".format(
408
+ assetCreation.status_code, assetCreation.text
409
+ )
410
+ )
411
+ else:
412
+ logger.info(
413
+ f"Successful asset creation {assetCreation.json()['id']}"
414
+ )
415
+
416
+ tagIds = [tag["id"] for tag in siteAssetDetail["tags"]]
417
+
418
+ else:
419
+ siteEntityDetail = self.get_site_entity_by_ID(org_asset_id)
420
+ assetCreation = self.create_site_entity_asset(
421
+ copyAssetCode,
422
+ copyAssetName,
423
+ copyAssetParentId,
424
+ description=siteEntityDetail["description"],
425
+ categoryId=siteEntityDetail["categoryId"],
426
+ calorificPower=siteEntityDetail["calorificPower"],
427
+ capacity=siteEntityDetail["capacity"],
428
+ coefficientOfPerformance=siteEntityDetail[
429
+ "coefficientOfPerformance"
430
+ ],
431
+ countingUnit=siteEntityDetail["countingUnit"],
432
+ eanCode=siteEntityDetail["eanCode"],
433
+ efficiency=siteEntityDetail["efficiency"],
434
+ energyEfficiencyRatio=siteEntityDetail[
435
+ "energyEfficiencyRatio"
436
+ ],
437
+ energyType=siteEntityDetail["energyType"],
438
+ energyUnit=siteEntityDetail["energyUnit"],
439
+ energyUsage=siteEntityDetail["energyUsage"],
440
+ energyVector=siteEntityDetail["energyVector"],
441
+ frigorificPowerm=siteEntityDetail["frigorificPowerm"],
442
+ gasLhvHhvConversionFactor=siteEntityDetail[
443
+ "gasLhvHhvConversionFactor"
444
+ ],
445
+ notes=siteEntityDetail["notes"],
446
+ )
447
+ if assetCreation.status_code != 200:
448
+ logger.error(
449
+ "Error on asset creattion {}: {}".format(
450
+ assetCreation.status_code, assetCreation.text
451
+ )
452
+ )
453
+ else:
454
+ logger.info(
455
+ f"Successful asset creation {assetCreation.json()['id']}"
456
+ )
457
+ tagIds = [tag["id"] for tag in siteEntityDetail["tags"]]
458
+
459
+ tagsLinking = self.link_tags_to_assets(
460
+ asset_ids=[assetCreation.json()["id"]], link_on_tagids=tagIds
461
+ )
462
+ if tagsLinking.status_code != 200:
463
+ logger.error(
464
+ "Error on asset tags linking {}: {}".format(
465
+ tagsLinking, tagsLinking.text
466
+ )
467
+ )
468
+ else:
469
+ logger.info("Successful tags linking")
470
+
471
+ if metricClonning:
472
+ orgAssetMetrics = self.get_metric_list_on_an_asset(org_asset_id)
473
+ metricIds = [metric["id"] for metric in orgAssetMetrics]
474
+
475
+ for metricList in split_list(metricIds, metricSplitGroups):
476
+ asset_metric_clonning = self.post_request(
477
+ "/api/mw/v1/metric/clone",
478
+ {
479
+ "assetId": org_asset_id,
480
+ "destinationAssetIds": [assetCreation.json()["id"]],
481
+ "skipMetricConfigurationIds": [0],
482
+ "metricConfigurationIds": metricList,
483
+ "skipMode": True,
484
+ },
485
+ )
486
+ if asset_metric_clonning.status_code != 200:
487
+ logger.error(
488
+ "Error on asset metric clonning {}: {}".format(
489
+ asset_metric_clonning.status_code,
490
+ asset_metric_clonning.text
491
+ )
492
+ )
493
+ else:
494
+ logger.info("Successful asset metric clonning")
495
+
496
+ def delete_energis_object_by_Id(self, energisObj, objID):
497
+ api_url = f"api/mw/v1/{energisObj}/{objID}"
498
+ url = self.env_url + api_url
499
+ r_energis = requests.delete(url, headers=self.headers, verify=False)
500
+ return r_energis
501
+
502
+ def get_energis_object_list(self, energisObj, **kwargs):
503
+ api_url = f"api/mw/v1/{energisObj}"
504
+ url = self.env_url + api_url
505
+
506
+ message = {}
507
+
508
+ for k, v in kwargs.items():
509
+ if k not in message.keys():
510
+ print(k, v)
511
+ message[k] = v
512
+ r_energis = requests.get(
513
+ url,
514
+ headers=self.headers,
515
+ json=message,
516
+ verify=False
517
+ )
518
+ return r_energis
519
+
520
+ def get_site_asset_list(
521
+ self,
522
+ asset_ids=[],
523
+ ancestor_asset_ids=[],
524
+ embed=[]
525
+ ):
526
+ api_url = "api/mw/v1/site"
527
+ url = self.env_url + api_url
528
+
529
+ if any([asset_ids, ancestor_asset_ids, embed]):
530
+ url = url + "?"
531
+ if asset_ids:
532
+ for id in asset_ids:
533
+ if url.endswith("?"):
534
+ url = url + f"asset-ids={id}"
535
+ else:
536
+ url = url + f"&asset-ids={id}"
537
+
538
+ if ancestor_asset_ids:
539
+ for id in ancestor_asset_ids:
540
+ if url.endswith("?"):
541
+ url = url + f"ancestor-asset-ids={id}"
542
+ else:
543
+ url = url + f"&ancestor-asset-ids={id}"
544
+
545
+ if embed:
546
+ for embed_str in embed:
547
+ if url.endswith("?"):
548
+ url = url + f"embed={embed_str}"
549
+ else:
550
+ url = url + f"&embed={embed_str}"
551
+
552
+ r_energis = requests.get(url, headers=self.headers, verify=False)
553
+ return r_energis
554
+
555
+ def get_energis_object_by_Id(self, energisObj, objID):
556
+ api_url = f"api/mw/v1/{energisObj}/{objID}"
557
+ url = self.env_url + api_url
558
+ r_energis = requests.get(
559
+ url,
560
+ headers=self.headers,
561
+ verify=False
562
+ ).json()
563
+ return r_energis
564
+
565
+ def get_site_entity_by_ID(self, entityID):
566
+ api_url = f"api/mw/v1/site-entity/{entityID}"
567
+ url = self.env_url + api_url
568
+ r_entity = requests.get(url, headers=self.headers, verify=False).json()
569
+ return r_entity
570
+
571
+ def get_site_by_ID(self, siteID):
572
+ api_url = f"api/mw/v1/site/{siteID}"
573
+ url = self.env_url + api_url
574
+ r_site = requests.get(url, headers=self.headers, verify=False).json()
575
+ return r_site
576
+
577
+ def get_asset_subtree_by_parentID(self, parentID, full_subtree=False):
578
+ api_url = "api/mw/v1/asset/"
579
+ url = self.env_url + api_url
580
+ r_subtree = requests.get(
581
+ url + str(parentID) + "/subtree",
582
+ headers=self.headers,
583
+ verify=False
584
+ ).json()
585
+
586
+ while not r_subtree[0]["assetId"] == parentID and not full_subtree:
587
+ r_subtree = r_subtree[0]["contents"]
588
+
589
+ return r_subtree
590
+
591
+ def get_asset_tree_by_parentID(self, parentID):
592
+ api_url = "api/mw/v1/asset/"
593
+ url = self.env_url + api_url
594
+ r_tree = requests.get(
595
+ url + str(parentID) + "/tree", headers=self.headers, verify=False
596
+ ).json()
597
+ return r_tree
598
+
599
+ def get_metric_list_on_an_asset(self, assetId):
600
+ api_url = f"api/mw/v1/metrics/{assetId}"
601
+ url = self.env_url + api_url
602
+ r_metric = requests.get(
603
+ # f"https://equans.energis.cloud/energiscloud-gateway/restful/api/mw/v1/metrics/{assetId}",
604
+ url,
605
+ headers=self.headers,
606
+ verify=False,
607
+ ).json()
608
+ return r_metric
609
+
610
+ def get_metric_detail_from_id(self, metricID):
611
+ api_url = f"api/mw/v1/metric/{metricID}"
612
+ url = self.env_url + api_url
613
+ r_metric = requests.get(
614
+ url,
615
+ headers=self.headers,
616
+ verify=False,
617
+ ).json()
618
+ return r_metric
619
+
620
+ def search_metric_by_name_on_an_asset(
621
+ self, assetID, search_str, string_exact=False
622
+ ):
623
+ metricListOnAsset = self.get_metric_list_on_an_asset(assetID)
624
+ if string_exact:
625
+ res = [
626
+ el
627
+ for el in metricListOnAsset
628
+ if search_str.lower() == el["externalName"].lower()
629
+ ]
630
+ else:
631
+ res = [
632
+ el
633
+ for el in metricListOnAsset
634
+ if search_str.lower() in el["externalName"].lower()
635
+ ]
636
+ return res
637
+
638
+ def get_filtered_assets(
639
+ self,
640
+ tagIds=[],
641
+ assetTypes=[],
642
+ categories=[],
643
+ **kwargs
644
+ ):
645
+ api_url = "api/mw/v1/asset/filter"
646
+ url = self.env_url + api_url
647
+
648
+ message = {
649
+ "tagIds": tagIds,
650
+ # "assetTypes" :assetTypes,
651
+ # "categories": categories
652
+ }
653
+
654
+ if assetTypes:
655
+ message["assetTypes"] = assetTypes
656
+ if categories:
657
+ message["categories"] = categories
658
+
659
+ # for k,v in kwargs.items():
660
+ # print(k,v)
661
+ # if not k in message.keys() and v:
662
+ # message[k] = v
663
+
664
+ r_assets = requests.post(
665
+ # "https://equans.energis.cloud/energiscloud-gateway/restful/api/mw/v1/asset/filter",
666
+ url,
667
+ headers=self.headers,
668
+ verify=False,
669
+ json=message,
670
+ )
671
+ return r_assets
672
+
673
+ def get_asset_detail_from_id(self, assetID):
674
+
675
+ api_url = f"api/mw/v1/asset/{assetID}"
676
+ url = self.env_url + api_url
677
+
678
+ r_asset = requests.get(
679
+ # "https://equans.energis.cloud/energiscloud-gateway/restful/api/mw/v1/asset/"
680
+ # + str(assetID),
681
+ url,
682
+ headers=self.headers,
683
+ verify=False,
684
+ ).json()
685
+ return r_asset
686
+
687
+ def energis_query(
688
+ self, metricID, date_from, date_to, timestep="FIFTEEN_MINUTE", **kwargs
689
+ ):
690
+ """
691
+ metricID:
692
+ date_from:
693
+ date_to:
694
+ timestep
695
+ There is a limit on number of point could be get 2000
696
+ """
697
+
698
+ api_url = "api/mw/v1/metric/query"
699
+ url = self.env_url + api_url
700
+
701
+ apiURL = kwargs.get(
702
+ "apiURL",
703
+ # "https://equans.energis.cloud/energiscloud-gateway/restful/api/mw/v1/metric/query",
704
+ url
705
+ )
706
+ counterMetricPeakRemoval = kwargs.get("peak_removal", True)
707
+ tzone_str = kwargs.get("tzone_str", "Europe/Brussels")
708
+ timestep = timestep.upper()
709
+
710
+ if not isinstance(
711
+ date_from,
712
+ dt.datetime
713
+ ) and isinstance(
714
+ date_to,
715
+ dt.datetime
716
+ ):
717
+ raise Exception("date_from and date_to must be datime instance")
718
+ if timestep not in ["FIFTEEN_MINUTE", "DAY", "HOUR", "MONTH", "YEAR"]:
719
+ raise Exception(
720
+ "timestep must be either 15min or day or hour or month or year"
721
+ )
722
+ if timestep == "DAY":
723
+ timestepsInSeconds = 24 * 3600
724
+ elif timestep == "FIFTEEN_MINUTE":
725
+ timestepsInSeconds = 15 * 60
726
+ elif timestep == "MONTH":
727
+ timestepsInSeconds = 24 * 3600 * 31
728
+ elif timestep == "YEAR":
729
+ timestepsInSeconds = 24 * 3600 * 366
730
+ else:
731
+ timestepsInSeconds = 3600
732
+
733
+ remainDataPointToGet = (
734
+ date_to - date_from
735
+ ).total_seconds() / timestepsInSeconds
736
+ r_df = pd.DataFrame()
737
+
738
+ while remainDataPointToGet > 2000:
739
+ body = {
740
+ "counterMetricPeakRemoval": counterMetricPeakRemoval,
741
+ "dateFrom": (
742
+ date_to - dt.timedelta(seconds=2000 * timestepsInSeconds)
743
+ ).isoformat(), # [:-3]#+"Z",
744
+ "dateTo": date_to.isoformat(), # [:-3]#+"Z",
745
+ "granularity": timestep,
746
+ "metricConfigurationId": metricID,
747
+ }
748
+ res = requests.post(
749
+ apiURL,
750
+ headers=self.headers,
751
+ json=body,
752
+ verify=False
753
+ )
754
+ r_data = res.json()
755
+
756
+ if "timeValues" in r_data.keys() and r_data["timeValues"]:
757
+ df = pd.DataFrame.from_dict(r_data["timeValues"])
758
+ df["@timestamp"] = pd.to_datetime(
759
+ df["timestamp"]
760
+ ).dt.tz_convert(
761
+ tzone_str
762
+ )
763
+ df.set_index("@timestamp", inplace=True)
764
+ df.sort_index(inplace=True)
765
+ df.drop(columns="timestamp", inplace=True)
766
+ if r_df.empty:
767
+ r_df = df
768
+ else:
769
+ r_df = pd.concat([r_df, df])
770
+ else:
771
+ print(
772
+ "no timeserie data for the periode "
773
+ f"from {date_from} to {date_to}"
774
+ )
775
+
776
+ remainDataPointToGet = remainDataPointToGet - 2000
777
+ date_to = date_to - dt.timedelta(seconds=2000 * timestepsInSeconds)
778
+
779
+ if remainDataPointToGet > 0:
780
+ body = {
781
+ "counterMetricPeakRemoval": True,
782
+ "dateFrom": date_from.isoformat(), # [:-3]#+"Z",
783
+ "dateTo": date_to.isoformat(), # [:-3]#+"Z",
784
+ "granularity": timestep,
785
+ "metricConfigurationId": metricID,
786
+ }
787
+ res = requests.post(
788
+ apiURL,
789
+ headers=self.headers,
790
+ json=body,
791
+ verify=False
792
+ )
793
+ r_data = res.json()
794
+
795
+ if "timeValues" in r_data.keys() and r_data["timeValues"]:
796
+ df = pd.DataFrame.from_dict(r_data["timeValues"])
797
+ df["@timestamp"] = pd.to_datetime(
798
+ df["timestamp"]
799
+ ).dt.tz_convert(
800
+ tzone_str
801
+ )
802
+ df.set_index("@timestamp", inplace=True)
803
+ df.sort_index(inplace=True)
804
+ df.drop(columns="timestamp", inplace=True)
805
+ if r_df.empty:
806
+ r_df = df
807
+ else:
808
+ r_df = pd.concat([r_df, df])
809
+ else:
810
+ logger.warning(
811
+ "no timeserie data for the periode "
812
+ f"from {date_from} to {date_to}"
813
+ )
814
+
815
+ return r_data, r_df
816
+
817
+ def energis_query_batch(
818
+ self,
819
+ metricIDs: list,
820
+ date_from,
821
+ date_to,
822
+ timestep="FIFTEEN_MINUTE",
823
+ **kwargs
824
+ ):
825
+
826
+ final_df = pd.DataFrame()
827
+
828
+ for metricID in metricIDs:
829
+ _, df = self.energis_query(
830
+ metricID,
831
+ date_from=date_from,
832
+ date_to=date_to,
833
+ timestep=timestep
834
+ )
835
+ df.rename(columns={"value": f"value_{metricID}"}, inplace=True)
836
+ if final_df.empty:
837
+ final_df = df
838
+ else:
839
+ final_df = pd.concat([final_df, df], axis=1)
840
+
841
+ return final_df
pyrapion/pyrapion.py ADDED
@@ -0,0 +1 @@
1
+ """Main module."""
pyrapion/quanstesx.py ADDED
@@ -0,0 +1,133 @@
1
+ # Description: This file contains the QuantesX API client
2
+ """docstring
3
+ """
4
+ import requests
5
+
6
+
7
+ class QuantesApiClient():
8
+ def __init__(self, api_key, env_url=None) -> None:
9
+ self.env_url = env_url
10
+ self.api_key = api_key
11
+ self.headers = {
12
+ "accept": "application/json",
13
+ "X-Api-Key": api_key
14
+ }
15
+ if self.env_url and not self.env_url[-1] == "/":
16
+ raise Exception(
17
+ "The environment url must be ended with a forward slash"
18
+ )
19
+ if not self.env_url:
20
+ raise Exception(
21
+ "The env_url is missing, please provide the env_url"
22
+ )
23
+
24
+ def get_sensor_list(self, site_name):
25
+ """
26
+ """
27
+ api_url = "/get_sensor_list"
28
+ url = self.env_url + api_url
29
+ params = {"site_name": site_name}
30
+ r_ds = requests.get(
31
+ url,
32
+ headers=self.headers,
33
+ params=params,
34
+ verify=False
35
+ )
36
+ if r_ds.status_code == 200:
37
+ return r_ds
38
+ else:
39
+ r_ds.raise_for_status()
40
+
41
+ def get_site_list(self):
42
+ """
43
+ """
44
+ api_url = "/get_site_list"
45
+ url = self.env_url + api_url
46
+ r_ds = requests.get(
47
+ url,
48
+ headers=self.headers,
49
+ verify=False
50
+ )
51
+ if r_ds.status_code == 200:
52
+ return r_ds
53
+ else:
54
+ r_ds.raise_for_status()
55
+
56
+ def get_site_calculated_data(self, site_names, date_from, date_to):
57
+ """
58
+ """
59
+ api_url = "/get_site_calculated_data"
60
+ url = self.env_url + api_url
61
+ params = {
62
+ "site_names": site_names,
63
+ "date_from": date_from,
64
+ "date_to": date_to
65
+ }
66
+ r_ds = requests.get(
67
+ url,
68
+ headers=self.headers,
69
+ params=params,
70
+ verify=False
71
+ )
72
+ if r_ds.status_code == 200:
73
+ return r_ds
74
+ else:
75
+ r_ds.raise_for_status()
76
+
77
+ def get_site_calculated_data_daily(
78
+ self,
79
+ site_names,
80
+ date_from,
81
+ date_to
82
+ ):
83
+ api_url = "/get_site_calculated_data_daily"
84
+ url = self.env_url + api_url
85
+ params = {
86
+ "site_names": site_names,
87
+ "date_from": date_from,
88
+ "date_to": date_to
89
+ }
90
+ r_ds = requests.get(
91
+ url,
92
+ headers=self.headers,
93
+ params=params,
94
+ verify=False
95
+ )
96
+ if r_ds.status_code == 200:
97
+ return r_ds
98
+ else:
99
+ r_ds.raise_for_status()
100
+
101
+ def get_site_raw_data(
102
+ self,
103
+ site_name,
104
+ client_name,
105
+ date_from=None,
106
+ date_to=None,
107
+ **kwargs
108
+ ):
109
+ """
110
+ """
111
+ api_url = "/get_site_raw_data"
112
+ url = self.env_url + api_url
113
+ params = {
114
+ "site_name": site_name,
115
+ "client_name": client_name
116
+ }
117
+ if date_from:
118
+ params["date_from"] = date_from
119
+ if date_to:
120
+ params["date_to"] = date_to
121
+ if kwargs:
122
+ params.update(kwargs)
123
+
124
+ r_ds = requests.get(
125
+ url,
126
+ headers=self.headers,
127
+ params=params,
128
+ verify=False
129
+ )
130
+ if r_ds.status_code == 200:
131
+ return r_ds
132
+ else:
133
+ r_ds.raise_for_status()
pyrapion/redex.py ADDED
@@ -0,0 +1,50 @@
1
+ import pandas as pd
2
+
3
+
4
+ def recalculate_redex_data(
5
+ energis_csv=None,
6
+ redex_html=None,
7
+ colname=None
8
+ ):
9
+
10
+ if energis_csv:
11
+ df = pd.read_csv(
12
+ energis_csv,
13
+ sep=";",
14
+ parse_dates=["DAY"],
15
+ date_format="%d/%m/%Y %H:%M"
16
+ )
17
+ else:
18
+ df = pd.DataFrame(columns=["DAY", colname])
19
+
20
+ df.dropna(inplace=True)
21
+ df.set_index("DAY", inplace=True)
22
+ col = df.columns[0]
23
+
24
+ html_dfs = pd.read_html(
25
+ redex_html,
26
+ # parse_dates=["Read date"],
27
+ # date_format="%d/%m/%Y",
28
+ )
29
+
30
+ for i, html_df in enumerate(html_dfs):
31
+ print(f"Table {i + 1}:")
32
+ html_df.loc[:, "Read date"] = pd.to_datetime(
33
+ html_df["Read date"],
34
+ format="%d/%m/%Y"
35
+ )
36
+ html_df.set_index("Read date", inplace=True)
37
+ html_df.loc[:, "Reading"] = html_df["Reading"].apply(
38
+ lambda x: x.replace(",", ".").replace(" ", "")
39
+ ).astype(float)
40
+ print(html_df) # Print the first few rows of each table
41
+
42
+ for i, row in html_df.iterrows():
43
+ if i not in df.index:
44
+ df.loc[i, col] = row["Reading"]
45
+
46
+ df[col] = df[col].astype(float)
47
+
48
+ new_df = df.resample("D").interpolate(method="linear")
49
+
50
+ return new_df
pyrapion/withphable.py ADDED
@@ -0,0 +1,84 @@
1
+ """
2
+ with phable v1.1.10
3
+
4
+ some modification
5
+ """
6
+ from phable.client import Client
7
+ import pandas as pd
8
+ import plotly.graph_objects as go
9
+
10
+ class WithPhableClient():
11
+ def __init__(self,uri,user,passwd):
12
+ self.uri = uri
13
+ self.username = user
14
+ self.password = passwd
15
+
16
+ def readAll(self,filter_str):
17
+ with Client(self.uri, self.username, self.password) as ph:
18
+ # fetch info about the Haystack server
19
+ point_meta = ph.read(
20
+ filter_str
21
+ )
22
+ if point_meta.empty:
23
+ print("Warning: No data")
24
+ else:
25
+ return point_meta
26
+
27
+ def hisRead(self,ids:list,datespan_str:str)->pd.DataFrame:
28
+ with Client(self.uri, self.username, self.password) as ph:
29
+ # fetch info about the Haystack server
30
+ batch_his_read_df = ph.his_read(
31
+ ids, datespan_str
32
+ )
33
+ if batch_his_read_df.empty:
34
+ print("Warning: no data")
35
+ else:
36
+ batch_his_read_df.index = batch_his_read_df.index.tz_localize(None)
37
+ return batch_his_read_df
38
+
39
+ def batch_his_read(self,filter_str:str, datespan_str:str, **kwargs):
40
+ """
41
+ filter_str: str
42
+ axon filter
43
+ datespan_str: str
44
+ date span
45
+ """
46
+ with Client(self.uri, self.username, self.password) as ph:
47
+ # fetch info about the Haystack server
48
+ point_meta = ph.read(
49
+ filter_str
50
+ )
51
+
52
+ batch_his_read_df = ph.his_read(
53
+ [id for id in point_meta["id"]], datespan_str
54
+ )
55
+ if batch_his_read_df.empty:
56
+ print("Warning: no data")
57
+ else:
58
+ batch_his_read_df.index = batch_his_read_df.index.tz_localize(None)
59
+ return point_meta, batch_his_read_df
60
+
61
+
62
+ # Plot layout
63
+ layout = go.Layout(
64
+ legend = dict(
65
+ font = dict(
66
+ size = 16,
67
+ ),
68
+ orientation = 'h'
69
+ ),
70
+ xaxis = dict(
71
+ # title = 'Time[Month]',
72
+ titlefont = dict(size = 18),
73
+ tickfont = dict(size = 18),
74
+ domain = [0.06,1]
75
+ ),
76
+ yaxis = dict(
77
+ # title = yaxis_title,
78
+ titlefont = dict(color ='black', size = 18),
79
+ tickfont= dict(color = 'black', size = 18),
80
+ anchor = 'x',
81
+ position = 0.02,
82
+ autorange=True
83
+ )
84
+ )
@@ -0,0 +1,64 @@
1
+ """
2
+ with phable v1.1.10
3
+
4
+ some modification
5
+ """
6
+ import pandas as pd
7
+ from phable.client import Client
8
+
9
+
10
+ class WithPhableClient():
11
+ def __init__(self, uri, user, passwd):
12
+ self.uri = uri
13
+ self.username = user
14
+ self.password = passwd
15
+
16
+ def readAll(self, filter_str):
17
+ with Client(self.uri, self.username, self.password) as ph:
18
+ # fetch info about the Haystack server
19
+ point_meta = ph.read(
20
+ filter_str
21
+ )
22
+ if point_meta.empty:
23
+ print("Warning: No data")
24
+ else:
25
+ return point_meta
26
+
27
+ def hisRead(self, ids: list, datespan_str: str) -> pd.DataFrame:
28
+ with Client(self.uri, self.username, self.password) as ph:
29
+ # fetch info about the Haystack server
30
+ batch_his_read_df = ph.his_read(
31
+ ids, datespan_str
32
+ )
33
+ if batch_his_read_df.empty:
34
+ print("Warning: no data")
35
+ else:
36
+ batch_his_read_df.index = batch_his_read_df.index.tz_localize(None)
37
+ return batch_his_read_df
38
+
39
+ def batch_his_read(
40
+ self,
41
+ filter_str: str,
42
+ datespan_str: str,
43
+ **kwargs
44
+ ):
45
+ """
46
+ filter_str: str
47
+ axon filter
48
+ datespan_str: str
49
+ date span
50
+ """
51
+ with Client(self.uri, self.username, self.password) as ph:
52
+ # fetch info about the Haystack server
53
+ point_meta = ph.read(
54
+ filter_str
55
+ )
56
+
57
+ batch_his_read_df = ph.his_read(
58
+ [id for id in point_meta["id"]], datespan_str
59
+ )
60
+ if batch_his_read_df.empty:
61
+ print("Warning: no data")
62
+ else:
63
+ batch_his_read_df.index = batch_his_read_df.index.tz_localize(None)
64
+ return point_meta, batch_his_read_df
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyrapion
3
+ Version: 0.1.0
4
+ Summary: Python package for helping restful api interaction
5
+ Home-page: https://github.com/longlevan/pyrapion
6
+ Author: Long Lê
7
+ Author-email: long.le-van@outlook.com
8
+ License: MIT
9
+ Keywords: pyrapion
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.6
15
+ Classifier: Programming Language :: Python :: 3.7
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Requires-Python: >=3.6
18
+ License-File: LICENSE
19
+ License-File: AUTHORS.rst
20
+ Requires-Dist: requests==2.31.0
21
+ Requires-Dist: pandas==2.2.2
22
+ Requires-Dist: phable==0.1.10
23
+ Requires-Dist: loguru==0.7.2
24
+ Requires-Dist: pytz==2024.1
25
+ Dynamic: author
26
+ Dynamic: author-email
27
+ Dynamic: classifier
28
+ Dynamic: description
29
+ Dynamic: home-page
30
+ Dynamic: keywords
31
+ Dynamic: license
32
+ Dynamic: license-file
33
+ Dynamic: requires-dist
34
+ Dynamic: requires-python
35
+ Dynamic: summary
36
+
37
+ ==========================================
38
+ Python Package for Restful API interactiON
39
+ ==========================================
40
+
41
+ Python package for helping restful api interaction
42
+
43
+ Features
44
+ --------
45
+
46
+ * TODO
47
+ * add list download for energis query
48
+
49
+ Credits
50
+ -------
51
+
52
+ This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
53
+
54
+ .. _Cookiecutter: https://github.com/audreyr/cookiecutter
55
+ .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
56
+
57
+
58
+ =======
59
+ History
60
+ =======
61
+
62
+ 0.1.0 (2023-08-18)
63
+ ------------------
64
+
65
+ * First release on PyPI.
@@ -0,0 +1,15 @@
1
+ pyrapion/__init__.py,sha256=tTyI8g5Lr_8aLPgKS9jK9M9XRgPkYdZBrE_wueTd0jo,166
2
+ pyrapion/cli.py,sha256=57GPWuIMMW0vhy97v1bxgcaTw1IAEtXb69gcn9HRDLs,458
3
+ pyrapion/energiscloud.py,sha256=UkvS8ar2gVqKCFqVPTPJHe-htEMZA9shxY7-ATahEFs,27652
4
+ pyrapion/pyrapion.py,sha256=vR5AaF0iel21LvsdcqwheoBz0SIj9K9I_Ub8M8oA98Y,20
5
+ pyrapion/quanstesx.py,sha256=YtLQBL-_LWSWMru4P8YRJsDkFfT-KLbv_wjjSBiq4Ps,3525
6
+ pyrapion/redex.py,sha256=JwM55g0IdF0lHmLS9d5S25OR2-IJr5T-R-WMEnt46fw,1317
7
+ pyrapion/withphable.py,sha256=PtRcox4SofUO1skjkURF69HA2rsYvKQKMkxlbrhIO_Q,2544
8
+ pyrapion/withphable_new.py,sha256=J3ou5L3NyiFFWFvPIMYv-109oCowP36RhOzK8RN-Q8c,1915
9
+ pyrapion-0.1.0.dist-info/licenses/AUTHORS.rst,sha256=zmHpWZnChXTJ4ADd5-v6Dch9FWGYlKcKUSU4dS0z_a0,170
10
+ pyrapion-0.1.0.dist-info/licenses/LICENSE,sha256=7SwYdbduiimXaVZa0XuEiQ3cGF1msytq2e0WRAEppEc,1089
11
+ pyrapion-0.1.0.dist-info/METADATA,sha256=qNU7vp6h2o3GITxOB7Ig1E19JNUWlDcCDbqxL_rvmx8,1689
12
+ pyrapion-0.1.0.dist-info/WHEEL,sha256=JNWh1Fm1UdwIQV075glCn4MVuCRs0sotJIq-J6rbxCU,109
13
+ pyrapion-0.1.0.dist-info/entry_points.txt,sha256=3L_dGGumhQwtkScKEZg8wH5IsTFrqRp0DvUmx5ODtrc,47
14
+ pyrapion-0.1.0.dist-info/top_level.txt,sha256=yeCHFSw5Z_oYw1fPn5dDk_C9rroO1x5XOMgM5xAscQ4,9
15
+ pyrapion-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,6 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pyrapion = pyrapion.cli:main
@@ -0,0 +1,13 @@
1
+ =======
2
+ Credits
3
+ =======
4
+
5
+ Development Lead
6
+ ----------------
7
+
8
+ * Long Lê <long.le-van@outlook.com>
9
+
10
+ Contributors
11
+ ------------
12
+
13
+ None yet. Why not be the first?
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Long Le-Van
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ pyrapion