|
| 1 | +from typing import Optional, Dict |
| 2 | +import requests |
| 3 | +from entsoe import __version__ |
| 4 | +import pandas as pd |
| 5 | +import json |
| 6 | +from io import BytesIO |
| 7 | +import zipfile |
| 8 | +from .decorators import check_expired |
| 9 | + |
| 10 | +# DOCS for entsoe file library: https://transparencyplatform.zendesk.com/hc/en-us/articles/35960137882129-File-Library-Guide |
| 11 | +# postman description: https://documenter.getpostman.com/view/28274243/2sB2qgfz3W |
| 12 | + |
| 13 | + |
| 14 | +class EntsoeFileClient: |
| 15 | + BASEURL = "https://fms.tp.entsoe.eu/" |
| 16 | + |
| 17 | + def __init__(self, username: str, pwd: str, session: Optional[requests.Session] = None, |
| 18 | + proxies: Optional[Dict] = None, timeout: Optional[int] = None |
| 19 | + ): |
| 20 | + self.proxies = proxies |
| 21 | + self.timeout = timeout |
| 22 | + self.username = username |
| 23 | + self.pwd = pwd |
| 24 | + if session is None: |
| 25 | + session = requests.Session() |
| 26 | + self.session = session |
| 27 | + self.session.headers.update({ |
| 28 | + 'user-agent': f'entsoe-py {__version__} (github.com/EnergieID/entsoe-py)' |
| 29 | + }) |
| 30 | + |
| 31 | + self.access_token = None |
| 32 | + self.expire = None |
| 33 | + |
| 34 | + self._update_token() |
| 35 | + |
| 36 | + def _update_token(self): |
| 37 | + # different url that other calls so hardcoded new one here |
| 38 | + r = self.session.post( |
| 39 | + 'https://keycloak.tp.entsoe.eu/realms/tp/protocol/openid-connect/token', data={ |
| 40 | + 'client_id': 'tp-fms-public', |
| 41 | + 'grant_type': 'password', |
| 42 | + 'username': self.username, |
| 43 | + 'password': self.pwd |
| 44 | + }, |
| 45 | + proxies=self.proxies, timeout=self.timeout |
| 46 | + ) |
| 47 | + r.raise_for_status() |
| 48 | + data = r.json() |
| 49 | + self.expire = pd.Timestamp.now(tz='europe/amsterdam') + pd.Timedelta(seconds=data['expires_in']) |
| 50 | + self.access_token = data['access_token'] |
| 51 | + |
| 52 | + @check_expired |
| 53 | + def list_folder(self, folder: str) -> dict: |
| 54 | + """ |
| 55 | + returns a dictionary of filename: unique file id |
| 56 | + """ |
| 57 | + if not folder.endswith('/'): |
| 58 | + folder += '/' |
| 59 | + r = self.session.post(self.BASEURL + "listFolder", |
| 60 | + data=json.dumps({ |
| 61 | + "path": "/TP_export/" + folder, |
| 62 | + "sorterList": [ |
| 63 | + { |
| 64 | + "key": "periodCovered.from", |
| 65 | + "ascending": True |
| 66 | + } |
| 67 | + ], |
| 68 | + "pageInfo": { |
| 69 | + "pageIndex": 0, |
| 70 | + "pageSize": 5000 # this should be enough for basically anything right now |
| 71 | + } |
| 72 | + }), |
| 73 | + headers={ |
| 74 | + 'Authorization': f'Bearer {self.access_token}', |
| 75 | + 'Content-Type': 'application/json' |
| 76 | + }, |
| 77 | + proxies=self.proxies, timeout=self.timeout) |
| 78 | + r.raise_for_status() |
| 79 | + data = r.json() |
| 80 | + return {x['name']: x['fileId'] for x in data['contentItemList']} |
| 81 | + |
| 82 | + @check_expired |
| 83 | + def download_single_file(self, folder, filename) -> pd.DataFrame: |
| 84 | + """ |
| 85 | + download a file by filename, it is important to split folder and filename here |
| 86 | + """ |
| 87 | + if not folder.endswith('/'): |
| 88 | + folder += '/' |
| 89 | + r = self.session.post(self.BASEURL + "downloadFileContent", |
| 90 | + data=json.dumps({ |
| 91 | + "folder": "/TP_export/" + folder, |
| 92 | + "filename": filename, |
| 93 | + "downloadAsZip": True, |
| 94 | + "topLevelFolder": "TP_export", |
| 95 | + }), |
| 96 | + headers={ |
| 97 | + 'Authorization': f'Bearer {self.access_token}', |
| 98 | + 'Content-Type': 'application/json' |
| 99 | + }) |
| 100 | + r.raise_for_status() |
| 101 | + stream = BytesIO(r.content) |
| 102 | + stream.seek(0) |
| 103 | + zf = zipfile.ZipFile(stream) |
| 104 | + with zf.open(zf.filelist[0].filename) as file: |
| 105 | + return pd.read_csv(file, sep='\t') |
| 106 | + |
| 107 | + @check_expired |
| 108 | + def download_multiple_files(self, file_ids: list) -> pd.DataFrame: |
| 109 | + """ |
| 110 | + for now when downloading multiple files only list of file ids is supported by this package |
| 111 | + """ |
| 112 | + r = self.session.post(self.BASEURL + "downloadFileContent", |
| 113 | + data=json.dumps({ |
| 114 | + "fileIdList": file_ids, |
| 115 | + "downloadAsZip": True, |
| 116 | + "topLevelFolder": "TP_export", |
| 117 | + }), |
| 118 | + headers={ |
| 119 | + 'Authorization': f'Bearer {self.access_token}', |
| 120 | + 'Content-Type': 'application/json' |
| 121 | + }, |
| 122 | + proxies=self.proxies, timeout=self.timeout) |
| 123 | + r.raise_for_status() |
| 124 | + stream = BytesIO(r.content) |
| 125 | + stream.seek(0) |
| 126 | + zf = zipfile.ZipFile(stream) |
| 127 | + df = [] |
| 128 | + for fz in zf.filelist: |
| 129 | + with zf.open(fz.filename) as file: |
| 130 | + df.append(pd.read_csv(file, sep='\t')) |
| 131 | + |
| 132 | + return pd.concat(df) |
| 133 | + |
0 commit comments