meteocatpy 0.0.20 → 1.0.1

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,26 @@
1
+ ## [1.0.1](https://github.com/figorr/meteocatpy/compare/v1.0.0...v1.0.1) (2025-02-05)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * 1.0.1 ([fc92ac1](https://github.com/figorr/meteocatpy/commit/fc92ac1fe40ff31cb0c38c5864d53209f42e128d))
7
+ * fix lightning api call code ([9abc092](https://github.com/figorr/meteocatpy/commit/9abc092b6951051279887d8ab09e2551371ea3b8))
8
+
9
+ ## [1.0.0](https://github.com/figorr/meteocatpy/compare/v0.0.20...v1.0.0) (2025-02-04)
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * 1.0.0 ([c237e77](https://github.com/figorr/meteocatpy/commit/c237e7736f3504f19a1bb2e39ed7edd3264de115))
15
+
16
+
17
+ ## [0.0.21](https://github.com/figorr/meteocatpy/compare/v0.0.20...v0.0.21) (2025-02-04)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * 1.0.0 ([c237e77](https://github.com/figorr/meteocatpy/commit/c237e7736f3504f19a1bb2e39ed7edd3264de115))
23
+
1
24
  ## [0.0.20](https://github.com/figorr/meteocatpy/compare/v0.0.19...v0.0.20) (2025-01-08)
2
25
 
3
26
 
package/filetree.txt CHANGED
@@ -22,6 +22,7 @@
22
22
  ├── forecast.py
23
23
  ├── helpers.py
24
24
  ├── infostation.py
25
+ ├── lightning.py
25
26
  ├── py.typed
26
27
  ├── quotes.py
27
28
  ├── stations.py
@@ -46,6 +47,7 @@
46
47
  ├── integration_test_complete.py
47
48
  ├── integration_test_forecast.py
48
49
  ├── integration_test_infostation.py
50
+ ├── integration_test_lightning.py
49
51
  ├── integration_test_quotes.py
50
52
  ├── integration_test_station_data.py
51
53
  ├── integration_test_stations.py
@@ -12,3 +12,4 @@ VARIABLES_URL = "/xema/v1/variables/mesurades/metadades"
12
12
  STATION_DATA_URL = "/xema/v1/estacions/mesurades/{codiEstacio}/{any}/{mes}/{dia}"
13
13
  UVI_DATA_URL = "/pronostic/v1/uvi/{codi_municipi}"
14
14
  ALERTS_URL = "/pronostic/v2/smp/episodis-oberts?data={any}-{mes}-{dia}Z"
15
+ LIGHTNING_URL = "/xdde/v1/informes/comarques/{codi_comarca}/{any}/{mes}/{dia}"
@@ -0,0 +1,135 @@
1
+ import aiohttp
2
+ import logging
3
+ import re
4
+ from datetime import datetime, timedelta
5
+ from .variables import MeteocatVariables
6
+ from .const import BASE_URL, LIGHTNING_URL
7
+ from .exceptions import (
8
+ BadRequestError,
9
+ ForbiddenError,
10
+ TooManyRequestsError,
11
+ InternalServerError,
12
+ UnknownAPIError,
13
+ )
14
+
15
+ _LOGGER = logging.getLogger(__name__)
16
+
17
+ class MeteocatLightning:
18
+ """Clase para interactuar con los datos de rayos de la API de Meteocat."""
19
+
20
+ def __init__(self, api_key: str):
21
+ """
22
+ Inicializa la clase MeteocatLightning.
23
+
24
+ Args:
25
+ api_key (str): Clave de API para autenticar las solicitudes.
26
+ """
27
+ self.api_key = api_key
28
+ self.headers = {
29
+ "Content-Type": "application/json",
30
+ "X-Api-Key": self.api_key,
31
+ }
32
+
33
+ @staticmethod
34
+ def get_current_date():
35
+ """
36
+ Obtiene la fecha actual en formato numérico.
37
+
38
+ Returns:
39
+ tuple: Año (YYYY), mes (MM), día (DD) como enteros.
40
+ """
41
+ now = datetime.now()
42
+ return now.year, now.month, now.day
43
+
44
+ @staticmethod
45
+ def get_previous_date():
46
+ """
47
+ Obtiene la fecha del día anterior en formato numérico.
48
+
49
+ Returns:
50
+ tuple: Año (YYYY), mes (MM), día (DD) como enteros.
51
+ """
52
+ yesterday = datetime.now() - timedelta(days=1)
53
+ return yesterday.year, yesterday.month, yesterday.day
54
+
55
+ async def get_lightning_data(self, region_id: str):
56
+ """
57
+ Obtiene los datos meteorológicos de rayos desde la API de Meteocat.
58
+
59
+ Args:
60
+ region_id (str): Código de la comarca.
61
+
62
+ Returns:
63
+ dict: Datos de rayos de la comarca.
64
+ """
65
+ any, mes, dia = self.get_current_date() # Calcula la fecha actual
66
+ url = f"{BASE_URL}{LIGHTNING_URL}".format(
67
+ codi_comarca=region_id, any=any, mes=f"{mes:02d}", dia=f"{dia:02d}"
68
+ )
69
+
70
+ async with aiohttp.ClientSession() as session:
71
+ try:
72
+ async with session.get(url, headers=self.headers) as response:
73
+ if response.status == 200:
74
+ return await response.json()
75
+
76
+ # Gestionar errores según el código de estado
77
+ if response.status == 400:
78
+ error_data = await response.json()
79
+ # Filtrar si el mensaje contiene una fecha válida
80
+ if "message" in error_data:
81
+ match = re.search(r'entre (\d{2}-\d{2}-\d{4}) i', error_data["message"])
82
+ if match:
83
+ last_valid_date = match.group(1) # Captura la última fecha válida
84
+ dia, mes, any = map(int, last_valid_date.split('-'))
85
+ # Intentar nuevamente con la última fecha válida
86
+ new_url = f"{BASE_URL}{LIGHTNING_URL}".format(
87
+ codi_comarca=region_id, any=any, mes=f"{mes:02d}", dia=f"{dia:02d}"
88
+ )
89
+ async with session.get(new_url, headers=self.headers) as new_response:
90
+ if new_response.status == 200:
91
+ return await new_response.json()
92
+ raise UnknownAPIError(
93
+ f"Failed with the valid date {last_valid_date}: {await new_response.text()}"
94
+ )
95
+
96
+ # Filtrar si el mensaje es "La comarca '<código>' no mesura la variable 'null'"
97
+ if re.search(r"La comarca '.*?' no mesura la variable 'null'", error_data.get("message", "")):
98
+ any, mes, dia = self.get_previous_date() # Obtener la fecha del día anterior
99
+ new_url = f"{BASE_URL}{LIGHTNING_URL}".format(
100
+ codi_comarca=region_id, any=any, mes=f"{mes:02d}", dia=f"{dia:02d}"
101
+ )
102
+ async with session.get(new_url, headers=self.headers) as new_response:
103
+ if new_response.status == 200:
104
+ return await new_response.json()
105
+ raise UnknownAPIError(
106
+ f"Failed with the previous date: {await new_response.text()}"
107
+ )
108
+
109
+ raise BadRequestError(await response.json())
110
+ elif response.status == 403:
111
+ error_data = await response.json()
112
+ if error_data.get("message") == "Forbidden":
113
+ raise ForbiddenError(error_data)
114
+ elif error_data.get("message") == "Missing Authentication Token":
115
+ raise ForbiddenError(error_data)
116
+ elif response.status == 429:
117
+ raise TooManyRequestsError(await response.json())
118
+ elif response.status == 500:
119
+ raise InternalServerError(await response.json())
120
+ else:
121
+ raise UnknownAPIError(
122
+ f"Unexpected error {response.status}: {await response.text()}"
123
+ )
124
+
125
+ except aiohttp.ClientError as e:
126
+ raise UnknownAPIError(
127
+ message=f"Error al conectar con la API de Meteocat: {str(e)}",
128
+ status_code=0,
129
+ )
130
+
131
+ except Exception as ex:
132
+ raise UnknownAPIError(
133
+ message=f"Error inesperado: {str(ex)}",
134
+ status_code=0,
135
+ )
@@ -1,2 +1,2 @@
1
1
  # version.py
2
- __version__ = "0.0.20"
2
+ __version__ = "1.0.1"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meteocatpy",
3
- "version": "0.0.20",
3
+ "version": "1.0.1",
4
4
  "description": "[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)\r [![Python version compatibility](https://img.shields.io/pypi/pyversions/meteocatpy)](https://pypi.org/project/meteocatpy)\r [![pipeline status](https://gitlab.com/figorr/meteocatpy/badges/master/pipeline.svg)](https://gitlab.com/figorr/meteocatpy/commits/master)",
5
5
  "main": "index.js",
6
6
  "directories": {
package/pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "meteocatpy"
3
- version = "0.0.20"
3
+ version = "1.0.1"
4
4
  description = "Script para obtener datos meteorológicos de la API de Meteocat"
5
5
  authors = ["figorr <jdcuartero@yahoo.es>"]
6
6
  license = "Apache-2.0"
@@ -0,0 +1,36 @@
1
+ import os
2
+ import pytest
3
+ import json
4
+ from dotenv import load_dotenv
5
+ from meteocatpy.lightning import MeteocatLightning
6
+
7
+ # Cargar variables desde el archivo .env
8
+ load_dotenv()
9
+
10
+ # Obtener los valores del archivo .env
11
+ API_KEY = os.getenv("METEOCAT_API_KEY_TEST")
12
+ REGION_CODI_TEST = os.getenv("REGION_CODI_TEST")
13
+
14
+ # Asegúrate de que las variables estén definidas
15
+ assert API_KEY, "API Key is required"
16
+ assert REGION_CODI_TEST, "Region codi test is required"
17
+
18
+ @pytest.mark.asyncio
19
+ async def test_lightning():
20
+ # Crear una instancia de MeteocatLightningData con la API Key
21
+ lightning_client = MeteocatLightning(API_KEY)
22
+
23
+ # Obtener los datos de rayos
24
+ lightning_data = await lightning_client.get_lightning_data(REGION_CODI_TEST)
25
+
26
+ print("Datos de la API:", lightning_data) # Para depuración
27
+
28
+ # Crear la carpeta si no existe
29
+ os.makedirs('tests/files', exist_ok=True)
30
+
31
+ # Guardar los datos de rayos en un archivo JSON
32
+ with open(f'tests/files/lightning_{REGION_CODI_TEST}.json', 'w', encoding='utf-8') as f:
33
+ json.dump(lightning_data, f, ensure_ascii=False, indent=4)
34
+
35
+ # Verificar que los datos de rayos sean una lista
36
+ assert isinstance(lightning_data, list), "La respuesta no es una lista"