meteocatpy 0.0.1__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.
- meteocatpy-0.0.1/AUTHORS.md +12 -0
- meteocatpy-0.0.1/LICENSE +194 -0
- meteocatpy-0.0.1/PKG-INFO +88 -0
- meteocatpy-0.0.1/README.md +62 -0
- meteocatpy-0.0.1/meteocatpy/README.md +62 -0
- meteocatpy-0.0.1/meteocatpy/__init__.py +27 -0
- meteocatpy-0.0.1/meteocatpy/const.py +10 -0
- meteocatpy-0.0.1/meteocatpy/data.py +77 -0
- meteocatpy-0.0.1/meteocatpy/exceptions.py +35 -0
- meteocatpy-0.0.1/meteocatpy/forecast.py +107 -0
- meteocatpy-0.0.1/meteocatpy/helpers.py +46 -0
- meteocatpy-0.0.1/meteocatpy/py.typed +0 -0
- meteocatpy-0.0.1/meteocatpy/stations.py +68 -0
- meteocatpy-0.0.1/meteocatpy/symbols.py +86 -0
- meteocatpy-0.0.1/meteocatpy/town.py +58 -0
- meteocatpy-0.0.1/meteocatpy/townstations.py +96 -0
- meteocatpy-0.0.1/meteocatpy/variables.py +59 -0
- meteocatpy-0.0.1/meteocatpy/version.py +2 -0
- meteocatpy-0.0.1/pyproject.toml +69 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Contributions to `meteocatpy`
|
|
2
|
+
|
|
3
|
+
## Owners
|
|
4
|
+
|
|
5
|
+
- Figorr [GitLab](https://gitlab.com/figorr) [GitHub](https://github.com/figorr)
|
|
6
|
+
|
|
7
|
+
## Maintainers
|
|
8
|
+
|
|
9
|
+
- Figorr [GitLab](https://gitlab.com/figorr) [GitHub](https://github.com/figorr)
|
|
10
|
+
|
|
11
|
+
## Contributors
|
|
12
|
+
|
meteocatpy-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
==============
|
|
3
|
+
|
|
4
|
+
_Version 2.0, January 2004_
|
|
5
|
+
_<<http://www.apache.org/licenses/>>_
|
|
6
|
+
|
|
7
|
+
### Terms and Conditions for use, reproduction, and distribution
|
|
8
|
+
|
|
9
|
+
#### 1. Definitions
|
|
10
|
+
|
|
11
|
+
“License” shall mean the terms and conditions for use, reproduction, and
|
|
12
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
“Licensor” shall mean the copyright owner or entity authorized by the copyright
|
|
15
|
+
owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
“Legal Entity” shall mean the union of the acting entity and all other entities
|
|
18
|
+
that control, are controlled by, or are under common control with that entity.
|
|
19
|
+
For the purposes of this definition, “control” means **(i)** the power, direct or
|
|
20
|
+
indirect, to cause the direction or management of such entity, whether by
|
|
21
|
+
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or **(iii)** beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
“You” (or “Your”) shall mean an individual or Legal Entity exercising
|
|
25
|
+
permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
“Source” form shall mean the preferred form for making modifications, including
|
|
28
|
+
but not limited to software source code, documentation source, and configuration
|
|
29
|
+
files.
|
|
30
|
+
|
|
31
|
+
“Object” form shall mean any form resulting from mechanical transformation or
|
|
32
|
+
translation of a Source form, including but not limited to compiled object code,
|
|
33
|
+
generated documentation, and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
“Work” shall mean the work of authorship, whether in Source or Object form, made
|
|
36
|
+
available under the License, as indicated by a copyright notice that is included
|
|
37
|
+
in or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
“Derivative Works” shall mean any work, whether in Source or Object form, that
|
|
40
|
+
is based on (or derived from) the Work and for which the editorial revisions,
|
|
41
|
+
annotations, elaborations, or other modifications represent, as a whole, an
|
|
42
|
+
original work of authorship. For the purposes of this License, Derivative Works
|
|
43
|
+
shall not include works that remain separable from, or merely link (or bind by
|
|
44
|
+
name) to the interfaces of, the Work and Derivative Works thereof.
|
|
45
|
+
|
|
46
|
+
“Contribution” shall mean any work of authorship, including the original version
|
|
47
|
+
of the Work and any modifications or additions to that Work or Derivative Works
|
|
48
|
+
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
|
49
|
+
by the copyright owner or by an individual or Legal Entity authorized to submit
|
|
50
|
+
on behalf of the copyright owner. For the purposes of this definition,
|
|
51
|
+
“submitted” means any form of electronic, verbal, or written communication sent
|
|
52
|
+
to the Licensor or its representatives, including but not limited to
|
|
53
|
+
communication on electronic mailing lists, source code control systems, and
|
|
54
|
+
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
|
55
|
+
the purpose of discussing and improving the Work, but excluding communication
|
|
56
|
+
that is conspicuously marked or otherwise designated in writing by the copyright
|
|
57
|
+
owner as “Not a Contribution.”
|
|
58
|
+
|
|
59
|
+
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
|
|
60
|
+
of whom a Contribution has been received by Licensor and subsequently
|
|
61
|
+
incorporated within the Work.
|
|
62
|
+
|
|
63
|
+
#### 2. Grant of Copyright License
|
|
64
|
+
|
|
65
|
+
Subject to the terms and conditions of this License, each Contributor hereby
|
|
66
|
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
|
67
|
+
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
|
68
|
+
publicly display, publicly perform, sublicense, and distribute the Work and such
|
|
69
|
+
Derivative Works in Source or Object form.
|
|
70
|
+
|
|
71
|
+
#### 3. Grant of Patent License
|
|
72
|
+
|
|
73
|
+
Subject to the terms and conditions of this License, each Contributor hereby
|
|
74
|
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
|
75
|
+
irrevocable (except as stated in this section) patent license to make, have
|
|
76
|
+
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
|
77
|
+
such license applies only to those patent claims licensable by such Contributor
|
|
78
|
+
that are necessarily infringed by their Contribution(s) alone or by combination
|
|
79
|
+
of their Contribution(s) with the Work to which such Contribution(s) was
|
|
80
|
+
submitted. If You institute patent litigation against any entity (including a
|
|
81
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
|
82
|
+
Contribution incorporated within the Work constitutes direct or contributory
|
|
83
|
+
patent infringement, then any patent licenses granted to You under this License
|
|
84
|
+
for that Work shall terminate as of the date such litigation is filed.
|
|
85
|
+
|
|
86
|
+
#### 4. Redistribution
|
|
87
|
+
|
|
88
|
+
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
|
89
|
+
in any medium, with or without modifications, and in Source or Object form,
|
|
90
|
+
provided that You meet the following conditions:
|
|
91
|
+
|
|
92
|
+
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
|
|
93
|
+
this License; and
|
|
94
|
+
* **(b)** You must cause any modified files to carry prominent notices stating that You
|
|
95
|
+
changed the files; and
|
|
96
|
+
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
|
|
97
|
+
all copyright, patent, trademark, and attribution notices from the Source form
|
|
98
|
+
of the Work, excluding those notices that do not pertain to any part of the
|
|
99
|
+
Derivative Works; and
|
|
100
|
+
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
|
|
101
|
+
Derivative Works that You distribute must include a readable copy of the
|
|
102
|
+
attribution notices contained within such NOTICE file, excluding those notices
|
|
103
|
+
that do not pertain to any part of the Derivative Works, in at least one of the
|
|
104
|
+
following places: within a NOTICE text file distributed as part of the
|
|
105
|
+
Derivative Works; within the Source form or documentation, if provided along
|
|
106
|
+
with the Derivative Works; or, within a display generated by the Derivative
|
|
107
|
+
Works, if and wherever such third-party notices normally appear. The contents of
|
|
108
|
+
the NOTICE file are for informational purposes only and do not modify the
|
|
109
|
+
License. You may add Your own attribution notices within Derivative Works that
|
|
110
|
+
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
|
111
|
+
provided that such additional attribution notices cannot be construed as
|
|
112
|
+
modifying the License.
|
|
113
|
+
|
|
114
|
+
You may add Your own copyright statement to Your modifications and may provide
|
|
115
|
+
additional or different license terms and conditions for use, reproduction, or
|
|
116
|
+
distribution of Your modifications, or for any such Derivative Works as a whole,
|
|
117
|
+
provided Your use, reproduction, and distribution of the Work otherwise complies
|
|
118
|
+
with the conditions stated in this License.
|
|
119
|
+
|
|
120
|
+
#### 5. Submission of Contributions
|
|
121
|
+
|
|
122
|
+
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
|
123
|
+
for inclusion in the Work by You to the Licensor shall be under the terms and
|
|
124
|
+
conditions of this License, without any additional terms or conditions.
|
|
125
|
+
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
|
126
|
+
any separate license agreement you may have executed with Licensor regarding
|
|
127
|
+
such Contributions.
|
|
128
|
+
|
|
129
|
+
#### 6. Trademarks
|
|
130
|
+
|
|
131
|
+
This License does not grant permission to use the trade names, trademarks,
|
|
132
|
+
service marks, or product names of the Licensor, except as required for
|
|
133
|
+
reasonable and customary use in describing the origin of the Work and
|
|
134
|
+
reproducing the content of the NOTICE file.
|
|
135
|
+
|
|
136
|
+
#### 7. Disclaimer of Warranty
|
|
137
|
+
|
|
138
|
+
Unless required by applicable law or agreed to in writing, Licensor provides the
|
|
139
|
+
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
|
|
140
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
|
141
|
+
including, without limitation, any warranties or conditions of TITLE,
|
|
142
|
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
|
143
|
+
solely responsible for determining the appropriateness of using or
|
|
144
|
+
redistributing the Work and assume any risks associated with Your exercise of
|
|
145
|
+
permissions under this License.
|
|
146
|
+
|
|
147
|
+
#### 8. Limitation of Liability
|
|
148
|
+
|
|
149
|
+
In no event and under no legal theory, whether in tort (including negligence),
|
|
150
|
+
contract, or otherwise, unless required by applicable law (such as deliberate
|
|
151
|
+
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
|
152
|
+
liable to You for damages, including any direct, indirect, special, incidental,
|
|
153
|
+
or consequential damages of any character arising as a result of this License or
|
|
154
|
+
out of the use or inability to use the Work (including but not limited to
|
|
155
|
+
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
|
156
|
+
any and all other commercial damages or losses), even if such Contributor has
|
|
157
|
+
been advised of the possibility of such damages.
|
|
158
|
+
|
|
159
|
+
#### 9. Accepting Warranty or Additional Liability
|
|
160
|
+
|
|
161
|
+
While redistributing the Work or Derivative Works thereof, You may choose to
|
|
162
|
+
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
|
163
|
+
other liability obligations and/or rights consistent with this License. However,
|
|
164
|
+
in accepting such obligations, You may act only on Your own behalf and on Your
|
|
165
|
+
sole responsibility, not on behalf of any other Contributor, and only if You
|
|
166
|
+
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
|
167
|
+
incurred by, or claims asserted against, such Contributor by reason of your
|
|
168
|
+
accepting any such warranty or additional liability.
|
|
169
|
+
|
|
170
|
+
_END OF TERMS AND CONDITIONS_
|
|
171
|
+
|
|
172
|
+
### APPENDIX: How to apply the Apache License to your work
|
|
173
|
+
|
|
174
|
+
To apply the Apache License to your work, attach the following boilerplate
|
|
175
|
+
notice, with the fields enclosed by brackets `[]` replaced with your own
|
|
176
|
+
identifying information. (Don't include the brackets!) The text should be
|
|
177
|
+
enclosed in the appropriate comment syntax for the file format. We also
|
|
178
|
+
recommend that a file or class name and description of purpose be included on
|
|
179
|
+
the same “printed page” as the copyright notice for easier identification within
|
|
180
|
+
third-party archives.
|
|
181
|
+
|
|
182
|
+
Copyright [yyyy] [name of copyright owner]
|
|
183
|
+
|
|
184
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
185
|
+
you may not use this file except in compliance with the License.
|
|
186
|
+
You may obtain a copy of the License at
|
|
187
|
+
|
|
188
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
189
|
+
|
|
190
|
+
Unless required by applicable law or agreed to in writing, software
|
|
191
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
192
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
193
|
+
See the License for the specific language governing permissions and
|
|
194
|
+
limitations under the License.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: meteocatpy
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Script para obtener datos meteorológicos de la API de Meteocat
|
|
5
|
+
Home-page: https://gitlab.com/figorr/meteocatpy
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Keywords: meteocatpy,meteocat
|
|
8
|
+
Author: figorr
|
|
9
|
+
Author-email: jdcuartero@yahoo.es
|
|
10
|
+
Requires-Python: ==3.12.7
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Requires-Dist: aiofiles (>=24.1.0,<25.0.0)
|
|
14
|
+
Requires-Dist: aiohttp (>=3.11.7,<4.0.0)
|
|
15
|
+
Requires-Dist: geopy (>=2.4.1,<3.0.0)
|
|
16
|
+
Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
|
|
17
|
+
Requires-Dist: python-semantic-release (>=9.14.0,<10.0.0)
|
|
18
|
+
Requires-Dist: requests (>=2.32.3,<3.0.0)
|
|
19
|
+
Requires-Dist: setuptools (>=75.5.0,<76.0.0)
|
|
20
|
+
Requires-Dist: simplejson (>=3.19.3,<4.0.0)
|
|
21
|
+
Requires-Dist: twine (>=5.1.1,<6.0.0)
|
|
22
|
+
Requires-Dist: tzdata (>=2024.2,<2025.0)
|
|
23
|
+
Requires-Dist: voluptuous (>=0.15.2,<0.16.0)
|
|
24
|
+
Project-URL: Repository, https://gitlab.com/figorr/meteocatpy
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# Meteocat Python Package for Meteocat Home Assistant Integration
|
|
28
|
+
|
|
29
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
30
|
+
[](https://pypi.org/project/meteocatpy)
|
|
31
|
+
[](https://gitlab.com/figorr/meteocatpy/commits/master)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
`meteocatpy` is a Python package to interact with the Meteocat API. Allows you to obtain meteorological data and lists of municipalities from the Meteocat API.
|
|
35
|
+
|
|
36
|
+
**NOTE:** Meteocat API requires to use an API_KEY, you should ask to (https://apidocs.meteocat.gencat.cat/documentacio/acces-ciutada-i-administracio/)
|
|
37
|
+
|
|
38
|
+
# Installation
|
|
39
|
+
|
|
40
|
+
You can install the package from PyPI using `pip`:
|
|
41
|
+
```bash
|
|
42
|
+
pip install meteocatpy
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
from meteocatpy.client import MeteocatClient
|
|
47
|
+
|
|
48
|
+
# Replace 'tu_api_key' with your actual API key
|
|
49
|
+
api_key = "tu_api_key"
|
|
50
|
+
client = MeteocatClient(api_key)
|
|
51
|
+
|
|
52
|
+
# Get a list of municipalities (asynchronous call)
|
|
53
|
+
municipis = await client.get_municipis()
|
|
54
|
+
print(municipis)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
# Credits
|
|
58
|
+
|
|
59
|
+
This is a personal project.
|
|
60
|
+
|
|
61
|
+
Authors:
|
|
62
|
+
- Figorr
|
|
63
|
+
|
|
64
|
+
# Contributing
|
|
65
|
+
|
|
66
|
+
If you would like to contribute to this project, please open an issue or create a pull request. I'd be happy to review your contributions!
|
|
67
|
+
|
|
68
|
+
1. [Check for open features/bugs](https://gitlab.com/figorr/meteocatpy/issues)
|
|
69
|
+
or [initiate a discussion on one](https://gitlab.com/figorr/meteocatpy/issues/new).
|
|
70
|
+
2. [Fork the repository](https://gitlab.com/figorr/meteocatpy/forks/new).
|
|
71
|
+
3. Install the dev environment: `make init`.
|
|
72
|
+
4. Enter the virtual environment: `pipenv shell`
|
|
73
|
+
5. Code your new feature or bug fix.
|
|
74
|
+
6. Write a test that covers your new functionality.
|
|
75
|
+
7. Update `README.md` with any new documentation.
|
|
76
|
+
8. Run tests and ensure 100% code coverage for your contribution: `make coverage`
|
|
77
|
+
9. Ensure you have no linting errors: `make lint`
|
|
78
|
+
10. Ensure you have typed your code correctly: `make typing`
|
|
79
|
+
11. Add yourself to `AUTHORS.md`.
|
|
80
|
+
12. Submit a pull request!
|
|
81
|
+
|
|
82
|
+
# License
|
|
83
|
+
|
|
84
|
+
[Apache-2.0](LICENSE). By providing a contribution, you agree the contribution is licensed under Apache-2.0.
|
|
85
|
+
|
|
86
|
+
# API Reference
|
|
87
|
+
|
|
88
|
+
[See the docs 📚](https://apidocs.meteocat.gencat.cat/section/informacio-general/).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Meteocat Python Package for Meteocat Home Assistant Integration
|
|
2
|
+
|
|
3
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
4
|
+
[](https://pypi.org/project/meteocatpy)
|
|
5
|
+
[](https://gitlab.com/figorr/meteocatpy/commits/master)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
`meteocatpy` is a Python package to interact with the Meteocat API. Allows you to obtain meteorological data and lists of municipalities from the Meteocat API.
|
|
9
|
+
|
|
10
|
+
**NOTE:** Meteocat API requires to use an API_KEY, you should ask to (https://apidocs.meteocat.gencat.cat/documentacio/acces-ciutada-i-administracio/)
|
|
11
|
+
|
|
12
|
+
# Installation
|
|
13
|
+
|
|
14
|
+
You can install the package from PyPI using `pip`:
|
|
15
|
+
```bash
|
|
16
|
+
pip install meteocatpy
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
from meteocatpy.client import MeteocatClient
|
|
21
|
+
|
|
22
|
+
# Replace 'tu_api_key' with your actual API key
|
|
23
|
+
api_key = "tu_api_key"
|
|
24
|
+
client = MeteocatClient(api_key)
|
|
25
|
+
|
|
26
|
+
# Get a list of municipalities (asynchronous call)
|
|
27
|
+
municipis = await client.get_municipis()
|
|
28
|
+
print(municipis)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
# Credits
|
|
32
|
+
|
|
33
|
+
This is a personal project.
|
|
34
|
+
|
|
35
|
+
Authors:
|
|
36
|
+
- Figorr
|
|
37
|
+
|
|
38
|
+
# Contributing
|
|
39
|
+
|
|
40
|
+
If you would like to contribute to this project, please open an issue or create a pull request. I'd be happy to review your contributions!
|
|
41
|
+
|
|
42
|
+
1. [Check for open features/bugs](https://gitlab.com/figorr/meteocatpy/issues)
|
|
43
|
+
or [initiate a discussion on one](https://gitlab.com/figorr/meteocatpy/issues/new).
|
|
44
|
+
2. [Fork the repository](https://gitlab.com/figorr/meteocatpy/forks/new).
|
|
45
|
+
3. Install the dev environment: `make init`.
|
|
46
|
+
4. Enter the virtual environment: `pipenv shell`
|
|
47
|
+
5. Code your new feature or bug fix.
|
|
48
|
+
6. Write a test that covers your new functionality.
|
|
49
|
+
7. Update `README.md` with any new documentation.
|
|
50
|
+
8. Run tests and ensure 100% code coverage for your contribution: `make coverage`
|
|
51
|
+
9. Ensure you have no linting errors: `make lint`
|
|
52
|
+
10. Ensure you have typed your code correctly: `make typing`
|
|
53
|
+
11. Add yourself to `AUTHORS.md`.
|
|
54
|
+
12. Submit a pull request!
|
|
55
|
+
|
|
56
|
+
# License
|
|
57
|
+
|
|
58
|
+
[Apache-2.0](LICENSE). By providing a contribution, you agree the contribution is licensed under Apache-2.0.
|
|
59
|
+
|
|
60
|
+
# API Reference
|
|
61
|
+
|
|
62
|
+
[See the docs 📚](https://apidocs.meteocat.gencat.cat/section/informacio-general/).
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Meteocat Python Package for Meteocat Home Assistant Integration
|
|
2
|
+
|
|
3
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
4
|
+
[](https://pypi.org/project/meteocatpy)
|
|
5
|
+
[](https://gitlab.com/figorr/meteocatpy/commits/master)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
`meteocatpy` is a Python package to interact with the Meteocat API. Allows you to obtain meteorological data and lists of municipalities from the Meteocat API.
|
|
9
|
+
|
|
10
|
+
**NOTE:** Meteocat API requires to use an API_KEY, you should ask to (https://apidocs.meteocat.gencat.cat/documentacio/acces-ciutada-i-administracio/)
|
|
11
|
+
|
|
12
|
+
# Installation
|
|
13
|
+
|
|
14
|
+
You can install the package from PyPI using `pip`:
|
|
15
|
+
```bash
|
|
16
|
+
pip install meteocatpy
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
from meteocatpy.town import MeteocatTown
|
|
21
|
+
|
|
22
|
+
# Replace 'tu_api_key' with your actual API key
|
|
23
|
+
API_KEY = "tu_api_key"
|
|
24
|
+
town_client = MeteocatTown(API_KEY)
|
|
25
|
+
|
|
26
|
+
# Get a list of municipalities (asynchronous call)
|
|
27
|
+
municipios_data = await town_client.get_municipis()
|
|
28
|
+
print(municipis)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
# Credits
|
|
32
|
+
|
|
33
|
+
This is a personal project.
|
|
34
|
+
|
|
35
|
+
Authors:
|
|
36
|
+
- Figorr
|
|
37
|
+
|
|
38
|
+
# Contributing
|
|
39
|
+
|
|
40
|
+
If you would like to contribute to this project, please open an issue or create a pull request. I'd be happy to review your contributions!
|
|
41
|
+
|
|
42
|
+
1. [Check for open features/bugs](https://gitlab.com/figorr/meteocatpy/issues)
|
|
43
|
+
or [initiate a discussion on one](https://gitlab.com/figorr/meteocatpy/issues/new).
|
|
44
|
+
2. [Fork the repository](https://gitlab.com/figorr/meteocatpy/forks/new).
|
|
45
|
+
3. Install the dev environment: `make init`.
|
|
46
|
+
4. Enter the virtual environment: `pipenv shell`
|
|
47
|
+
5. Code your new feature or bug fix.
|
|
48
|
+
6. Write a test that covers your new functionality.
|
|
49
|
+
7. Update `README.md` with any new documentation.
|
|
50
|
+
8. Run tests and ensure 100% code coverage for your contribution: `make coverage`
|
|
51
|
+
9. Ensure you have no linting errors: `make lint`
|
|
52
|
+
10. Ensure you have typed your code correctly: `make typing`
|
|
53
|
+
11. Add yourself to `AUTHORS.md`.
|
|
54
|
+
12. Submit a pull request!
|
|
55
|
+
|
|
56
|
+
# License
|
|
57
|
+
|
|
58
|
+
[Apache-2.0](LICENSE). By providing a contribution, you agree the contribution is licensed under Apache-2.0.
|
|
59
|
+
|
|
60
|
+
# API Reference
|
|
61
|
+
|
|
62
|
+
[See the docs 📚](https://apidocs.meteocat.gencat.cat/section/informacio-general/).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""METEOCAT API.
|
|
2
|
+
|
|
3
|
+
Python Package to collect data from Meteocat API and interact with Meteocat Home Assistant Integration
|
|
4
|
+
SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
|
|
6
|
+
For more details about this API, please refer to the documentation at
|
|
7
|
+
https://gitlab.com/figorr/meteocatpy
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
# meteocatpy/__init__.py
|
|
11
|
+
from .town import MeteocatTown
|
|
12
|
+
from .forecast import MeteocatForecast
|
|
13
|
+
from .symbols import MeteocatSymbols
|
|
14
|
+
from .stations import MeteocatStations
|
|
15
|
+
from .townstations import MeteocatTownStations
|
|
16
|
+
from .data import MeteocatStationData
|
|
17
|
+
from .variables import MeteocatVariables
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"MeteocatTown",
|
|
21
|
+
"MeteocatForecast",
|
|
22
|
+
"MeteocatSymbols",
|
|
23
|
+
"MeteocatStations",
|
|
24
|
+
"MeteocatTownStations",
|
|
25
|
+
"MeteocatStationData",
|
|
26
|
+
"MeteocatVariables"
|
|
27
|
+
]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""meteocatpy constants."""
|
|
2
|
+
BASE_URL = "https://api.meteo.cat"
|
|
3
|
+
MUNICIPIS_LIST_URL = "/referencia/v1/municipis"
|
|
4
|
+
MUNICIPIS_HORA_URL = "/pronostic/v1/municipalHoraria/{codi}"
|
|
5
|
+
MUNICIPIS_DIA_URL = "/pronostic/v1/municipal/{codi}"
|
|
6
|
+
SYMBOLS_URL = "/referencia/v1/simbols"
|
|
7
|
+
STATIONS_LIST_URL = "/xema/v1/estacions/metadades"
|
|
8
|
+
STATIONS_MUNICIPI_URL = "/xema/v1/representatives/metadades/municipis/{codi_municipi}/variables/{codi_variable}"
|
|
9
|
+
VARIABLES_URL = "/xema/v1/variables/mesurades/metadades"
|
|
10
|
+
STATION_DATA_URL = "/xema/v1/estacions/mesurades/{codiEstacio}/{any}/{mes}/{dia}"
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from .const import BASE_URL, STATION_DATA_URL
|
|
4
|
+
from .exceptions import BadRequestError, ForbiddenError, TooManyRequestsError, InternalServerError, UnknownAPIError
|
|
5
|
+
|
|
6
|
+
class MeteocatStationData:
|
|
7
|
+
"""Clase para interactuar con los datos de la estación en la API de Meteocat."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, api_key: str):
|
|
10
|
+
"""
|
|
11
|
+
Inicializa la clase MeteocatStationData.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
15
|
+
"""
|
|
16
|
+
self.api_key = api_key
|
|
17
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
18
|
+
|
|
19
|
+
@staticmethod
|
|
20
|
+
def get_current_date():
|
|
21
|
+
"""
|
|
22
|
+
Obtiene la fecha actual en formato numérico.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
tuple: Año (YYYY), mes (MM), día (DD) como enteros.
|
|
26
|
+
"""
|
|
27
|
+
now = datetime.now()
|
|
28
|
+
return now.year, now.month, now.day
|
|
29
|
+
|
|
30
|
+
async def get_station_data(self, station_id: str):
|
|
31
|
+
"""
|
|
32
|
+
Obtiene los datos meteorológicos para el código de estación y fecha actual.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
codiEstacio (str): Código de la estación.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
dict: Datos meteorológicos de la estación para la fecha actual.
|
|
39
|
+
"""
|
|
40
|
+
year, month, day = self.get_current_date() # Calcula la fecha actual
|
|
41
|
+
url = f"{BASE_URL}{STATION_DATA_URL}".format(
|
|
42
|
+
codiEstacio=station_id, any=year, mes=f"{month:02d}", dia=f"{day:02d}"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
async with aiohttp.ClientSession() as session:
|
|
46
|
+
try:
|
|
47
|
+
async with session.get(url, headers=self.headers) as response:
|
|
48
|
+
if response.status == 200:
|
|
49
|
+
return await response.json()
|
|
50
|
+
|
|
51
|
+
# Gestionar errores según el código de estado
|
|
52
|
+
if response.status == 400:
|
|
53
|
+
raise BadRequestError(await response.json())
|
|
54
|
+
elif response.status == 403:
|
|
55
|
+
error_data = await response.json()
|
|
56
|
+
if error_data.get("message") == "Forbidden":
|
|
57
|
+
raise ForbiddenError(error_data)
|
|
58
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
59
|
+
raise ForbiddenError(error_data)
|
|
60
|
+
elif response.status == 429:
|
|
61
|
+
raise TooManyRequestsError(await response.json())
|
|
62
|
+
elif response.status == 500:
|
|
63
|
+
raise InternalServerError(await response.json())
|
|
64
|
+
else:
|
|
65
|
+
raise UnknownAPIError(f"Unexpected error {response.status}: {await response.text()}")
|
|
66
|
+
|
|
67
|
+
except aiohttp.ClientError as e:
|
|
68
|
+
raise UnknownAPIError(
|
|
69
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
70
|
+
status_code=0,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
except Exception as ex:
|
|
74
|
+
raise UnknownAPIError(
|
|
75
|
+
message=f"Error inesperado: {str(ex)}",
|
|
76
|
+
status_code=0,
|
|
77
|
+
)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""METEOCAT API exceptions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
class MeteocatAPIError(Exception):
|
|
6
|
+
"""Clase base para todos los errores de la API de Meteocat."""
|
|
7
|
+
def __init__(self, message: str, status_code: int, aws_info: dict = None):
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.status_code = status_code
|
|
10
|
+
self.aws_info = aws_info
|
|
11
|
+
|
|
12
|
+
class BadRequestError(MeteocatAPIError):
|
|
13
|
+
"""Error 400: Bad request."""
|
|
14
|
+
def __init__(self, message: str, aws_info: dict = None):
|
|
15
|
+
super().__init__(message, 400, aws_info)
|
|
16
|
+
|
|
17
|
+
class ForbiddenError(MeteocatAPIError):
|
|
18
|
+
"""Error 403: Forbidden."""
|
|
19
|
+
def __init__(self, message: str, aws_info: dict = None):
|
|
20
|
+
super().__init__(message, 403, aws_info)
|
|
21
|
+
|
|
22
|
+
class TooManyRequestsError(MeteocatAPIError):
|
|
23
|
+
"""Error 429: Too many requests."""
|
|
24
|
+
def __init__(self, message: str, aws_info: dict = None):
|
|
25
|
+
super().__init__(message, 429, aws_info)
|
|
26
|
+
|
|
27
|
+
class InternalServerError(MeteocatAPIError):
|
|
28
|
+
"""Error 500: Internal server error."""
|
|
29
|
+
def __init__(self, message: str, aws_info: dict = None):
|
|
30
|
+
super().__init__(message, 500, aws_info)
|
|
31
|
+
|
|
32
|
+
class UnknownAPIError(MeteocatAPIError):
|
|
33
|
+
"""Error desconocido de la API."""
|
|
34
|
+
def __init__(self, message: str, status_code: int, aws_info: dict = None):
|
|
35
|
+
super().__init__(message, status_code, aws_info)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from .const import BASE_URL, MUNICIPIS_HORA_URL, MUNICIPIS_DIA_URL
|
|
3
|
+
from .exceptions import BadRequestError, ForbiddenError, TooManyRequestsError, InternalServerError, UnknownAPIError
|
|
4
|
+
|
|
5
|
+
class MeteocatForecast:
|
|
6
|
+
"""Clase para interactuar con las predicciones de la API de Meteocat."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, api_key: str):
|
|
9
|
+
"""
|
|
10
|
+
Inicializa la clase MeteocatForecast.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
14
|
+
"""
|
|
15
|
+
self.api_key = api_key
|
|
16
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
17
|
+
|
|
18
|
+
async def get_prediccion_horaria(self, town_id: str):
|
|
19
|
+
"""
|
|
20
|
+
Obtiene la predicción horaria a 72 horas para un municipio.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
codi (str): Código del municipio.
|
|
24
|
+
|
|
25
|
+
Returns:
|
|
26
|
+
dict: Predicción horaria para el municipio.
|
|
27
|
+
"""
|
|
28
|
+
url = f"{BASE_URL}{MUNICIPIS_HORA_URL.format(codi=town_id)}"
|
|
29
|
+
async with aiohttp.ClientSession() as session:
|
|
30
|
+
try:
|
|
31
|
+
async with session.get(url, headers=self.headers) as response:
|
|
32
|
+
if response.status == 200:
|
|
33
|
+
return await response.json()
|
|
34
|
+
|
|
35
|
+
# Gestionar errores según el código de estado
|
|
36
|
+
if response.status == 400:
|
|
37
|
+
raise BadRequestError(await response.json())
|
|
38
|
+
elif response.status == 403:
|
|
39
|
+
error_data = await response.json()
|
|
40
|
+
if error_data.get("message") == "Forbidden":
|
|
41
|
+
raise ForbiddenError(error_data)
|
|
42
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
43
|
+
raise ForbiddenError(error_data)
|
|
44
|
+
elif response.status == 429:
|
|
45
|
+
raise TooManyRequestsError(await response.json())
|
|
46
|
+
elif response.status == 500:
|
|
47
|
+
raise InternalServerError(await response.json())
|
|
48
|
+
else:
|
|
49
|
+
raise UnknownAPIError(f"Unexpected error {response.status}: {await response.text()}")
|
|
50
|
+
|
|
51
|
+
except aiohttp.ClientError as e:
|
|
52
|
+
raise UnknownAPIError(
|
|
53
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
54
|
+
status_code=0,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
except Exception as ex:
|
|
58
|
+
raise UnknownAPIError(
|
|
59
|
+
message=f"Error inesperado: {str(ex)}",
|
|
60
|
+
status_code=0,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def get_prediccion_diaria(self, town_id: str):
|
|
65
|
+
"""
|
|
66
|
+
Obtiene la predicción diaria a 8 días para un municipio.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
codi (str): Código del municipio.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
dict: Predicción diaria para el municipio.
|
|
73
|
+
"""
|
|
74
|
+
url = f"{BASE_URL}{MUNICIPIS_DIA_URL.format(codi=town_id)}"
|
|
75
|
+
async with aiohttp.ClientSession() as session:
|
|
76
|
+
try:
|
|
77
|
+
async with session.get(url, headers=self.headers) as response:
|
|
78
|
+
if response.status == 200:
|
|
79
|
+
return await response.json()
|
|
80
|
+
|
|
81
|
+
# Gestionar errores según el código de estado
|
|
82
|
+
if response.status == 400:
|
|
83
|
+
raise BadRequestError(await response.json())
|
|
84
|
+
elif response.status == 403:
|
|
85
|
+
error_data = await response.json()
|
|
86
|
+
if error_data.get("message") == "Forbidden":
|
|
87
|
+
raise ForbiddenError(error_data)
|
|
88
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
89
|
+
raise ForbiddenError(error_data)
|
|
90
|
+
elif response.status == 429:
|
|
91
|
+
raise TooManyRequestsError(await response.json())
|
|
92
|
+
elif response.status == 500:
|
|
93
|
+
raise InternalServerError(await response.json())
|
|
94
|
+
else:
|
|
95
|
+
raise UnknownAPIError(f"Unexpected error {response.status}: {await response.text()}")
|
|
96
|
+
|
|
97
|
+
except aiohttp.ClientError as e:
|
|
98
|
+
raise UnknownAPIError(
|
|
99
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
100
|
+
status_code=0,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
except Exception as ex:
|
|
104
|
+
raise UnknownAPIError(
|
|
105
|
+
message=f"Error inesperado: {str(ex)}",
|
|
106
|
+
status_code=0,
|
|
107
|
+
)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Meteocat Helpers."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from zoneinfo import ZoneInfo
|
|
8
|
+
|
|
9
|
+
TZ_UTC = ZoneInfo("UTC")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def dict_nested_value(data: dict[str, Any] | None, keys: list[str] | None) -> Any:
|
|
13
|
+
"""Get value from dict with nested keys."""
|
|
14
|
+
if keys is None or len(keys) == 0:
|
|
15
|
+
return None
|
|
16
|
+
for key in keys or {}:
|
|
17
|
+
if data is not None:
|
|
18
|
+
data = data.get(key)
|
|
19
|
+
return data
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_current_datetime(tz: ZoneInfo = TZ_UTC, replace: bool = True) -> datetime:
|
|
23
|
+
"""Return current datetime in UTC."""
|
|
24
|
+
cur_dt = datetime.now(tz=tz)
|
|
25
|
+
if replace:
|
|
26
|
+
cur_dt = cur_dt.replace(minute=0, second=0, microsecond=0)
|
|
27
|
+
return cur_dt
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parse_api_timestamp(timestamp: str, tz: ZoneInfo = TZ_UTC) -> datetime:
|
|
31
|
+
"""Parse API timestamp into datetime."""
|
|
32
|
+
return datetime.fromisoformat(timestamp).replace(tzinfo=tz)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def slugify(value: str, allow_unicode: bool = False) -> str:
|
|
36
|
+
"""Convert string to a valid file name."""
|
|
37
|
+
if allow_unicode:
|
|
38
|
+
value = unicodedata.normalize("NFKC", value)
|
|
39
|
+
else:
|
|
40
|
+
value = (
|
|
41
|
+
unicodedata.normalize("NFKD", value)
|
|
42
|
+
.encode("ascii", "ignore")
|
|
43
|
+
.decode("ascii")
|
|
44
|
+
)
|
|
45
|
+
value = re.sub(r"[^\w\s]", "-", value.lower())
|
|
46
|
+
return re.sub(r"[-\s]+", "-", value).strip("-_")
|
|
File without changes
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from .const import BASE_URL, STATIONS_LIST_URL
|
|
3
|
+
from .exceptions import (
|
|
4
|
+
BadRequestError,
|
|
5
|
+
ForbiddenError,
|
|
6
|
+
TooManyRequestsError,
|
|
7
|
+
InternalServerError,
|
|
8
|
+
UnknownAPIError
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
class MeteocatStations:
|
|
12
|
+
"""
|
|
13
|
+
Clase para interactuar con la API de Meteocat y obtener la lista de todas las estaciones."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, api_key: str):
|
|
16
|
+
"""
|
|
17
|
+
Inicializa la clase MeteocatStations.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
21
|
+
"""
|
|
22
|
+
self.api_key = api_key
|
|
23
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
24
|
+
|
|
25
|
+
async def get_stations(self):
|
|
26
|
+
"""
|
|
27
|
+
Obtiene la lista de estaciones.
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
dict: Lista de estaciones.
|
|
31
|
+
"""
|
|
32
|
+
url = f"{BASE_URL}{STATIONS_LIST_URL}"
|
|
33
|
+
async with aiohttp.ClientSession() as session:
|
|
34
|
+
try:
|
|
35
|
+
async with session.get(url, headers=self.headers) as response:
|
|
36
|
+
if response.status == 200:
|
|
37
|
+
return await response.json()
|
|
38
|
+
|
|
39
|
+
# Gestionar errores según el código de estado
|
|
40
|
+
if response.status == 400:
|
|
41
|
+
raise BadRequestError(await response.json())
|
|
42
|
+
elif response.status == 403:
|
|
43
|
+
error_data = await response.json()
|
|
44
|
+
if error_data.get("message") == "Forbidden":
|
|
45
|
+
raise ForbiddenError(error_data)
|
|
46
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
47
|
+
raise ForbiddenError(error_data)
|
|
48
|
+
elif response.status == 429:
|
|
49
|
+
raise TooManyRequestsError(await response.json())
|
|
50
|
+
elif response.status == 500:
|
|
51
|
+
raise InternalServerError(await response.json())
|
|
52
|
+
else:
|
|
53
|
+
raise UnknownAPIError(
|
|
54
|
+
f"Unexpected error {response.status}: {await response.text()}"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
except aiohttp.ClientError as e:
|
|
58
|
+
raise UnknownAPIError(
|
|
59
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
60
|
+
status_code=0,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
except Exception as ex:
|
|
64
|
+
raise UnknownAPIError(
|
|
65
|
+
message=f"Error inesperado: {str(ex)}",
|
|
66
|
+
status_code=0,
|
|
67
|
+
)
|
|
68
|
+
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from .const import BASE_URL, SYMBOLS_URL
|
|
3
|
+
from .exceptions import BadRequestError, ForbiddenError, TooManyRequestsError, InternalServerError, UnknownAPIError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MeteocatSymbols:
|
|
7
|
+
"""Clase para interactuar con la API de símbolos de Meteocat."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, api_key: str):
|
|
10
|
+
"""
|
|
11
|
+
Inicializa la clase MeteocatSymbols.
|
|
12
|
+
|
|
13
|
+
Args:
|
|
14
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
15
|
+
"""
|
|
16
|
+
self.api_key = api_key
|
|
17
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
18
|
+
self.symbols_map = {}
|
|
19
|
+
|
|
20
|
+
async def fetch_symbols(self):
|
|
21
|
+
url = f"{BASE_URL}{SYMBOLS_URL}"
|
|
22
|
+
async with aiohttp.ClientSession() as session:
|
|
23
|
+
try:
|
|
24
|
+
async with session.get(url, headers=self.headers) as response:
|
|
25
|
+
if response.status == 200:
|
|
26
|
+
data = await response.json()
|
|
27
|
+
print(data) # Esto te mostrará la estructura completa en la consola
|
|
28
|
+
|
|
29
|
+
# Asegurarse de que `data` sea una lista de categorías
|
|
30
|
+
if isinstance(data, list):
|
|
31
|
+
self.symbols_map = {}
|
|
32
|
+
for category in data:
|
|
33
|
+
if "valors" in category:
|
|
34
|
+
# Guardamos los valores de cada categoría
|
|
35
|
+
self.symbols_map[category["nom"]] = category["valors"]
|
|
36
|
+
return data # Devolvemos todo el conjunto de datos
|
|
37
|
+
|
|
38
|
+
else:
|
|
39
|
+
raise UnknownAPIError(f"Unexpected structure of data: {data}", status_code=response.status)
|
|
40
|
+
|
|
41
|
+
# Gestionar errores de respuesta
|
|
42
|
+
if response.status == 400:
|
|
43
|
+
raise BadRequestError(await response.json())
|
|
44
|
+
elif response.status == 403:
|
|
45
|
+
error_data = await response.json()
|
|
46
|
+
if error_data.get("message") == "Forbidden":
|
|
47
|
+
raise ForbiddenError(error_data)
|
|
48
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
49
|
+
raise ForbiddenError(error_data)
|
|
50
|
+
elif response.status == 429:
|
|
51
|
+
raise TooManyRequestsError(await response.json())
|
|
52
|
+
elif response.status == 500:
|
|
53
|
+
raise InternalServerError(await response.json())
|
|
54
|
+
else:
|
|
55
|
+
raise UnknownAPIError(f"Unexpected error {response.status}: {await response.text()}", status_code=response.status)
|
|
56
|
+
|
|
57
|
+
except aiohttp.ClientError as e:
|
|
58
|
+
raise UnknownAPIError(
|
|
59
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
60
|
+
status_code=0,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
except Exception as ex:
|
|
64
|
+
raise UnknownAPIError(
|
|
65
|
+
message=f"Error inesperado: {str(ex)}",
|
|
66
|
+
status_code=0,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def get_description(self, category: str, code: int) -> str:
|
|
72
|
+
"""
|
|
73
|
+
Obtiene la descripción de un código de símbolo dentro de una categoría.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
category (str): Nombre de la categoría (e.g., "cel").
|
|
77
|
+
code (int): Código del símbolo.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
str: Descripción del símbolo. Retorna 'Desconocido' si el código no está en el mapeo.
|
|
81
|
+
"""
|
|
82
|
+
category_symbols = self.symbols_map.get(category, [])
|
|
83
|
+
for symbol in category_symbols:
|
|
84
|
+
if symbol["codi"] == str(code): # El código es devuelto como string por la API
|
|
85
|
+
return symbol["descripcio"]
|
|
86
|
+
return "Desconocido"
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from .const import BASE_URL, MUNICIPIS_LIST_URL
|
|
3
|
+
from .exceptions import BadRequestError, ForbiddenError, TooManyRequestsError, InternalServerError, UnknownAPIError
|
|
4
|
+
|
|
5
|
+
class MeteocatTown:
|
|
6
|
+
"""Clase para interactuar con la lista de municipios de la API de Meteocat."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, api_key: str):
|
|
9
|
+
"""
|
|
10
|
+
Inicializa la clase MeteocatTown.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
14
|
+
"""
|
|
15
|
+
self.api_key = api_key
|
|
16
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
17
|
+
|
|
18
|
+
async def get_municipis(self):
|
|
19
|
+
"""
|
|
20
|
+
Obtiene la lista de municipios desde la API de Meteocat.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
dict: Datos de los municipios.
|
|
24
|
+
"""
|
|
25
|
+
url = f"{BASE_URL}{MUNICIPIS_LIST_URL}"
|
|
26
|
+
async with aiohttp.ClientSession() as session:
|
|
27
|
+
try:
|
|
28
|
+
async with session.get(url, headers=self.headers) as response:
|
|
29
|
+
if response.status == 200:
|
|
30
|
+
return await response.json()
|
|
31
|
+
|
|
32
|
+
# Gestionar errores según el código de estado
|
|
33
|
+
if response.status == 400:
|
|
34
|
+
raise BadRequestError(await response.json())
|
|
35
|
+
elif response.status == 403:
|
|
36
|
+
error_data = await response.json()
|
|
37
|
+
if error_data.get("message") == "Forbidden":
|
|
38
|
+
raise ForbiddenError(error_data)
|
|
39
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
40
|
+
raise ForbiddenError(error_data)
|
|
41
|
+
elif response.status == 429:
|
|
42
|
+
raise TooManyRequestsError(await response.json())
|
|
43
|
+
elif response.status == 500:
|
|
44
|
+
raise InternalServerError(await response.json())
|
|
45
|
+
else:
|
|
46
|
+
raise UnknownAPIError(f"Unexpected error {response.status}: {await response.text()}")
|
|
47
|
+
|
|
48
|
+
except aiohttp.ClientError as e:
|
|
49
|
+
raise UnknownAPIError(
|
|
50
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
51
|
+
status_code=0,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
except Exception as ex:
|
|
55
|
+
raise UnknownAPIError(
|
|
56
|
+
message=f"Error inesperado: {str(ex)}",
|
|
57
|
+
status_code=0,
|
|
58
|
+
)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from .stations import MeteocatStations # Importamos la clase MeteocatStations
|
|
3
|
+
from .const import BASE_URL, STATIONS_MUNICIPI_URL
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
BadRequestError,
|
|
6
|
+
ForbiddenError,
|
|
7
|
+
TooManyRequestsError,
|
|
8
|
+
InternalServerError,
|
|
9
|
+
UnknownAPIError,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
class MeteocatTownStations:
|
|
13
|
+
"""
|
|
14
|
+
Clase para interactuar con la API de Meteocat y obtener
|
|
15
|
+
las estaciones representativas de un municipio para una variable específica.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, api_key: str):
|
|
19
|
+
"""
|
|
20
|
+
Inicializa la clase MeteocatTownStations.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
24
|
+
"""
|
|
25
|
+
self.api_key = api_key
|
|
26
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
27
|
+
self.stations_service = MeteocatStations(api_key) # Instancia de MeteocatStations
|
|
28
|
+
|
|
29
|
+
async def get_town_stations(self, town_id: str, variable_id: str):
|
|
30
|
+
"""
|
|
31
|
+
Obtiene la lista de estaciones representativas para un municipio y una variable específica,
|
|
32
|
+
enriqueciendo los datos con el nombre de las estaciones.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
codi_municipi (str): Código del municipio.
|
|
36
|
+
codi_variable (str): Código de la variable.
|
|
37
|
+
|
|
38
|
+
Returns:
|
|
39
|
+
list: Datos de las estaciones representativas con nombres añadidos.
|
|
40
|
+
"""
|
|
41
|
+
# Obtener la lista completa de estaciones
|
|
42
|
+
all_stations = await self.stations_service.get_stations()
|
|
43
|
+
|
|
44
|
+
# Crear un diccionario para acceder rápidamente a los nombres por código
|
|
45
|
+
station_names = {station["codi"]: station["nom"] for station in all_stations}
|
|
46
|
+
|
|
47
|
+
# URL para obtener las estaciones del municipio y la variable
|
|
48
|
+
url = f"{BASE_URL}{STATIONS_MUNICIPI_URL}".format(
|
|
49
|
+
codi_municipi=town_id, codi_variable=variable_id
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
async with aiohttp.ClientSession() as session:
|
|
53
|
+
try:
|
|
54
|
+
async with session.get(url, headers=self.headers) as response:
|
|
55
|
+
if response.status == 200:
|
|
56
|
+
data = await response.json()
|
|
57
|
+
|
|
58
|
+
# Enriquecer el JSON con los nombres de las estaciones
|
|
59
|
+
for town in data:
|
|
60
|
+
for variable in town.get("variables", []):
|
|
61
|
+
for station in variable.get("estacions", []):
|
|
62
|
+
codi = station["codi"]
|
|
63
|
+
station["nom"] = station_names.get(codi, "Nombre desconocido")
|
|
64
|
+
|
|
65
|
+
return data
|
|
66
|
+
|
|
67
|
+
# Gestionar errores según el código de estado
|
|
68
|
+
if response.status == 400:
|
|
69
|
+
raise BadRequestError(await response.json())
|
|
70
|
+
elif response.status == 403:
|
|
71
|
+
error_data = await response.json()
|
|
72
|
+
if error_data.get("message") == "Forbidden":
|
|
73
|
+
raise ForbiddenError(error_data)
|
|
74
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
75
|
+
raise ForbiddenError(error_data)
|
|
76
|
+
elif response.status == 429:
|
|
77
|
+
raise TooManyRequestsError(await response.json())
|
|
78
|
+
elif response.status == 500:
|
|
79
|
+
raise InternalServerError(await response.json())
|
|
80
|
+
else:
|
|
81
|
+
raise UnknownAPIError(
|
|
82
|
+
f"Unexpected error {response.status}: {await response.text()}"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
except aiohttp.ClientError as e:
|
|
86
|
+
raise UnknownAPIError(
|
|
87
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
88
|
+
status_code=0,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
except Exception as ex:
|
|
92
|
+
raise UnknownAPIError(
|
|
93
|
+
message=f"Error inesperado: {str(ex)}",
|
|
94
|
+
status_code=0,
|
|
95
|
+
)
|
|
96
|
+
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import aiohttp
|
|
2
|
+
from .const import BASE_URL, VARIABLES_URL
|
|
3
|
+
from .exceptions import BadRequestError, ForbiddenError, TooManyRequestsError, InternalServerError, UnknownAPIError
|
|
4
|
+
|
|
5
|
+
class MeteocatVariables:
|
|
6
|
+
"""Clase para interactuar con la lista de variables de la API de Meteocat."""
|
|
7
|
+
|
|
8
|
+
def __init__(self, api_key: str):
|
|
9
|
+
"""
|
|
10
|
+
Inicializa la clase MeteocatVariables.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
api_key (str): Clave de API para autenticar las solicitudes.
|
|
14
|
+
"""
|
|
15
|
+
self.api_key = api_key
|
|
16
|
+
self.headers = {"X-Api-Key": self.api_key}
|
|
17
|
+
|
|
18
|
+
async def get_variables(self):
|
|
19
|
+
"""
|
|
20
|
+
Obtiene la lista de variables desde la API de Meteocat.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
dict: Datos de las variables.
|
|
24
|
+
"""
|
|
25
|
+
url = f"{BASE_URL}{VARIABLES_URL}"
|
|
26
|
+
async with aiohttp.ClientSession() as session:
|
|
27
|
+
try:
|
|
28
|
+
async with session.get(url, headers=self.headers) as response:
|
|
29
|
+
if response.status == 200:
|
|
30
|
+
return await response.json()
|
|
31
|
+
|
|
32
|
+
# Gestionar errores según el código de estado
|
|
33
|
+
if response.status == 400:
|
|
34
|
+
raise BadRequestError(await response.json())
|
|
35
|
+
elif response.status == 403:
|
|
36
|
+
error_data = await response.json()
|
|
37
|
+
if error_data.get("message") == "Forbidden":
|
|
38
|
+
raise ForbiddenError(error_data)
|
|
39
|
+
elif error_data.get("message") == "Missing Authentication Token":
|
|
40
|
+
raise ForbiddenError(error_data)
|
|
41
|
+
elif response.status == 429:
|
|
42
|
+
raise TooManyRequestsError(await response.json())
|
|
43
|
+
elif response.status == 500:
|
|
44
|
+
raise InternalServerError(await response.json())
|
|
45
|
+
else:
|
|
46
|
+
raise UnknownAPIError(f"Unexpected error {response.status}: {await response.text()}")
|
|
47
|
+
|
|
48
|
+
except aiohttp.ClientError as e:
|
|
49
|
+
raise UnknownAPIError(
|
|
50
|
+
message=f"Error al conectar con la API de Meteocat: {str(e)}",
|
|
51
|
+
status_code=0,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
except Exception as ex:
|
|
55
|
+
raise UnknownAPIError(
|
|
56
|
+
message=f"Error inesperado: {str(ex)}",
|
|
57
|
+
status_code=0,
|
|
58
|
+
)
|
|
59
|
+
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "meteocatpy"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = "Script para obtener datos meteorológicos de la API de Meteocat"
|
|
5
|
+
authors = ["figorr <jdcuartero@yahoo.es>"]
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
readme = "README.md"
|
|
8
|
+
repository = "https://gitlab.com/figorr/meteocatpy"
|
|
9
|
+
keywords = ['meteocatpy', 'meteocat']
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
[tool.poetry.dependencies]
|
|
13
|
+
python = "3.12.7"
|
|
14
|
+
requests = "^2.32.3"
|
|
15
|
+
python-dotenv = "^1.0.1"
|
|
16
|
+
simplejson = "^3.19.3"
|
|
17
|
+
setuptools = "^75.5.0"
|
|
18
|
+
python-semantic-release = "^9.14.0"
|
|
19
|
+
twine = "^5.1.1"
|
|
20
|
+
aiofiles = "^24.1.0"
|
|
21
|
+
voluptuous = "^0.15.2"
|
|
22
|
+
geopy = "^2.4.1"
|
|
23
|
+
tzdata = "^2024.2"
|
|
24
|
+
aiohttp = "^3.11.7"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
[tool.semantic_release]
|
|
28
|
+
branch = "master" # Define la rama desde la que se harán los lanzamientos
|
|
29
|
+
version_source = "commit" # Determina la versión basada en los commits
|
|
30
|
+
version_variable = "meteocatpy/version.py:__version__" # Ubicación de la variable de versión
|
|
31
|
+
changelog = { file = "CHANGELOG.md" } # Genera el changelog en el archivo especificado
|
|
32
|
+
upload_to_pypi = false # Sube automáticamente la versión a PyPI
|
|
33
|
+
ci = false # Cambiar a false si no usas CI/CD
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
[build-system]
|
|
37
|
+
requires = ["poetry-core"]
|
|
38
|
+
build-backend = "poetry.core.masonry.api"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
[tool.poetry.dev-dependencies]
|
|
42
|
+
aresponses = "*"
|
|
43
|
+
detox = "*"
|
|
44
|
+
flake8 = "*"
|
|
45
|
+
mypy = "*"
|
|
46
|
+
pydocstyle = "*"
|
|
47
|
+
pylint = "*"
|
|
48
|
+
pytest-aiohttp = "*"
|
|
49
|
+
pytest-cov = "*"
|
|
50
|
+
python-semantic-release = "^9.14.0"
|
|
51
|
+
tox = "*"
|
|
52
|
+
safety = ">=1.8.7"
|
|
53
|
+
black = { version = ">19.10b0", allow-prereleases = true }
|
|
54
|
+
Sphinx = ">=3.5.0,<7.0.0"
|
|
55
|
+
autoapi = ">=2.0.1"
|
|
56
|
+
sphinx-rtd-theme = "^0.5.1"
|
|
57
|
+
m2r2 = ">=0.2.7"
|
|
58
|
+
tomlkit = ">=0.7.0"
|
|
59
|
+
sphinx-autoapi = ">=1.7.0"
|
|
60
|
+
sphinx-copybutton = ">=0.3.1"
|
|
61
|
+
pipdeptree = "^2.2.1"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
[tool.poetry.group.dev.dependencies]
|
|
65
|
+
pyupgrade = "^3.4.0"
|
|
66
|
+
pre-commit = "^3.3.1"
|
|
67
|
+
pytest = "^8.3.3"
|
|
68
|
+
pytest-asyncio = "^0.24.0"
|
|
69
|
+
syrupy = "^4.7.2"
|