cloudnet-api-client 0.12.13__tar.gz → 0.12.14__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.
Files changed (33) hide show
  1. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/workflows/publish.yml +1 -1
  2. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/CHANGELOG.md +4 -0
  3. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/PKG-INFO +25 -2
  4. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/README.md +23 -0
  5. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/client.py +115 -11
  6. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/dl.py +2 -2
  7. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/version.py +1 -1
  8. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/pyproject.toml +2 -1
  9. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/test_client.py +53 -0
  10. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/dataportal.env +0 -0
  11. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/db.env +0 -0
  12. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/docker-compose.yml +0 -0
  13. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/initdb.d/init-dbs.sh +0 -0
  14. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/ss.env +0 -0
  15. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.github/workflows/test.yml +0 -0
  16. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.gitignore +0 -0
  17. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/.pre-commit-config.yaml +0 -0
  18. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/LICENSE +0 -0
  19. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/__init__.py +0 -0
  20. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/containers.py +0 -0
  21. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/py.typed +0 -0
  22. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/cloudnet_api_client/utils.py +0 -0
  23. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20140205_hyytiala_classification.nc +0 -0
  24. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250711_kenttarova_l3-cf_ecmwf.nc +0 -0
  25. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250711_kenttarova_l3-cf_era5-1-12.nc +0 -0
  26. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250711_kenttarova_l3-cf_era5-7-18.nc +0 -0
  27. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250801_Magurele_CHM170137_000.nc +0 -0
  28. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250803_JOYCE_WST_01m.dat +0 -0
  29. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250808_Granada_CHM170119_0045_000.nc +0 -0
  30. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250808_hyytiala_iwc-Z-T-method.nc +0 -0
  31. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250814_bucharest_classification.nc +0 -0
  32. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250821_limassol_parsivel_41582c49.nc +0 -0
  33. {cloudnet_api_client-0.12.13 → cloudnet_api_client-0.12.14}/tests/data/20250822_leipzig-lim_ecmwf-open.nc +0 -0
@@ -30,7 +30,7 @@ jobs:
30
30
  echo "name=cloudnet-api-client $version" >> $GITHUB_OUTPUT
31
31
  id: changelog
32
32
  - name: Create release
33
- uses: softprops/action-gh-release@v2
33
+ uses: softprops/action-gh-release@v3
34
34
  with:
35
35
  name: ${{ steps.changelog.outputs.name }}
36
36
  body_path: ${{ github.workspace }}-CHANGELOG.txt
@@ -5,6 +5,10 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## 0.12.14 – 2026-11-30
9
+
10
+ - Add `submit` method for data submission
11
+
8
12
  ## 0.12.13 – 2026-10-28
9
13
 
10
14
  - Verify checksum on file download
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cloudnet-api-client
3
- Version: 0.12.13
3
+ Version: 0.12.14
4
4
  Summary: Cloudnet API client
5
5
  Author-email: Simo Tukiainen <simo.tukiainen@fmi.fi>
6
+ License-Expression: MIT
6
7
  License-File: LICENSE
7
8
  Classifier: Development Status :: 3 - Alpha
8
9
  Classifier: Intended Audience :: Science/Research
9
- Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
@@ -252,6 +252,29 @@ Parameters:
252
252
  There's also an asynchronous version of this function:
253
253
  `cloudnet_api_client.adownload`. It's useful for usage inside Jupyter notebook.
254
254
 
255
+ ### `APIClient().submit()` &rarr; `None`
256
+
257
+ Submit a raw data file to the Cloudnet data portal. The file metadata is uploaded
258
+ first, then the file itself. If the file has already been received by the server,
259
+ the data upload is skipped. See the
260
+ [data upload documentation](https://docs.cloudnet.fmi.fi/api/data-upload.html).
261
+
262
+ Parameters:
263
+
264
+ | name | type | default | example |
265
+ | -------------- | ------------------- | ------- | ---------------------------------------------------- |
266
+ | filename | `str` or `PathLike` | | "20250801_Magurele_CHM170137_000.nc" |
267
+ | date | `str` or `date` | | "2025-08-01" |
268
+ | instrument_id | `str` | | "chm15k" |
269
+ | instrument_pid | `str` | | "https://hdl.handle.net/21.12132/3.c60c931fac9d43f0" |
270
+ | site_id | `str` | | "bucharest" |
271
+ | username | `str` | | |
272
+ | password | `str` | | |
273
+ | tags | `Iterable[str]` | `None` | ["co"] |
274
+
275
+ The upload requires HTTP Basic authentication via the `username` and `password`
276
+ parameters.
277
+
255
278
  ## License
256
279
 
257
280
  MIT
@@ -223,6 +223,29 @@ Parameters:
223
223
  There's also an asynchronous version of this function:
224
224
  `cloudnet_api_client.adownload`. It's useful for usage inside Jupyter notebook.
225
225
 
226
+ ### `APIClient().submit()` &rarr; `None`
227
+
228
+ Submit a raw data file to the Cloudnet data portal. The file metadata is uploaded
229
+ first, then the file itself. If the file has already been received by the server,
230
+ the data upload is skipped. See the
231
+ [data upload documentation](https://docs.cloudnet.fmi.fi/api/data-upload.html).
232
+
233
+ Parameters:
234
+
235
+ | name | type | default | example |
236
+ | -------------- | ------------------- | ------- | ---------------------------------------------------- |
237
+ | filename | `str` or `PathLike` | | "20250801_Magurele_CHM170137_000.nc" |
238
+ | date | `str` or `date` | | "2025-08-01" |
239
+ | instrument_id | `str` | | "chm15k" |
240
+ | instrument_pid | `str` | | "https://hdl.handle.net/21.12132/3.c60c931fac9d43f0" |
241
+ | site_id | `str` | | "bucharest" |
242
+ | username | `str` | | |
243
+ | password | `str` | | |
244
+ | tags | `Iterable[str]` | `None` | ["co"] |
245
+
246
+ The upload requires HTTP Basic authentication via the `username` and `password`
247
+ parameters.
248
+
226
249
  ## License
227
250
 
228
251
  MIT
@@ -2,19 +2,21 @@
2
2
 
3
3
  This module provides the main APIClient class for interacting with the Cloudnet
4
4
  data portal API. It includes methods for fetching sites, products, instruments,
5
- models, files, and downloading data.
5
+ models, files, downloading data, and submitting raw data files.
6
6
  """
7
7
 
8
8
  import asyncio
9
9
  import calendar
10
10
  import datetime
11
+ import logging
11
12
  import os
12
13
  import re
13
14
  import warnings
15
+ from collections.abc import Iterable
14
16
  from dataclasses import asdict
15
17
  from os import PathLike
16
18
  from pathlib import Path
17
- from urllib.parse import urljoin
19
+ from typing import Any
18
20
  from uuid import UUID
19
21
 
20
22
  import requests
@@ -60,15 +62,18 @@ from .utils import (
60
62
  _parse_datetime,
61
63
  _set_of_ids,
62
64
  _validate_type,
65
+ md5sum,
63
66
  )
64
67
 
68
+ logger = logging.getLogger(__name__)
69
+
65
70
 
66
71
  class APIClient:
67
72
  """Client for the Cloudnet data portal API.
68
73
 
69
74
  This class provides methods to interact with the Cloudnet API, including
70
75
  fetching sites, products, instruments, models, and file metadata, as well
71
- as downloading files.
76
+ as downloading and submitting files.
72
77
 
73
78
  Attributes:
74
79
  base_url: The base URL of the Cloudnet API.
@@ -82,19 +87,18 @@ class APIClient:
82
87
 
83
88
  def __init__(
84
89
  self,
85
- base_url: str = "https://cloudnet.fmi.fi/api/",
90
+ base_url: str = "https://cloudnet.fmi.fi/",
86
91
  session: requests.Session | None = None,
87
92
  ) -> None:
88
93
  """Initialize the APIClient.
89
94
 
90
95
  Args:
91
96
  base_url: The base URL of the Cloudnet API. Defaults to
92
- "https://cloudnet.fmi.fi/api/".
97
+ "https://cloudnet.fmi.fi/".
93
98
  session: An optional requests.Session to use for API calls.
94
99
  If not provided, a new session will be created.
95
100
  """
96
- if not base_url.endswith("/"):
97
- base_url += "/"
101
+ base_url = base_url.removesuffix("/").removesuffix("/api") + "/"
98
102
  self.base_url = base_url
99
103
  self.session = session or _make_session()
100
104
 
@@ -612,7 +616,7 @@ class APIClient:
612
616
  """
613
617
  if not isinstance(date, datetime.date):
614
618
  date = datetime.date.fromisoformat(date)
615
- payload = {"date": date}
619
+ payload = {"date": date.strftime("%Y-%m-%d")}
616
620
  res = self._get(f"sites/{site_id}/locations", params=payload)[0]
617
621
  return MeanLocation(
618
622
  time=date,
@@ -643,7 +647,7 @@ class APIClient:
643
647
  """
644
648
  if not isinstance(date, datetime.date):
645
649
  date = datetime.date.fromisoformat(date)
646
- payload = {"date": date, "raw": "1"}
650
+ payload = {"date": date.strftime("%Y-%m-%d"), "raw": "1"}
647
651
  locations = self._get(f"sites/{site_id}/locations", params=payload)
648
652
  return [
649
653
  RawLocation(
@@ -702,9 +706,93 @@ class APIClient:
702
706
  """
703
707
  if not isinstance(date, datetime.date):
704
708
  date = datetime.date.fromisoformat(date)
705
- payload = {"instrumentPid": instrument_pid, "date": date.isoformat()}
709
+ payload = {
710
+ "instrumentPid": instrument_pid,
711
+ "date": date.strftime("%Y-%m-%d"),
712
+ }
706
713
  return self._get("calibration", params=payload)[0]
707
714
 
715
+ def submit(
716
+ self,
717
+ filename: str | PathLike,
718
+ date: datetime.date | str,
719
+ instrument_id: str,
720
+ instrument_pid: str,
721
+ site_id: str,
722
+ username: str,
723
+ password: str,
724
+ tags: Iterable[str] | None = None,
725
+ ) -> None:
726
+ """Submit a raw data file to the Cloudnet data portal.
727
+
728
+ File submission has two stages: metadata and data upload. The metadata
729
+ is uploaded first with a POST request to /upload/metadata/, after which
730
+ the file itself is uploaded with a PUT request to /upload/data/<md5>.
731
+ If the server responds that the file has already been received (HTTP
732
+ 409), the data upload is skipped. See
733
+ https://docs.cloudnet.fmi.fi/api/data-upload.html for details.
734
+
735
+ Args:
736
+ filename: Path to the local file to submit.
737
+ date: UTC date (YYYY-MM-DD) of the first data point in
738
+ the file.
739
+ instrument_id: Instrument ID, e.g. "chm15k". Must be one of the IDs
740
+ listed in https://cloudnet.fmi.fi/api/instruments/.
741
+ instrument_pid: Persistent identifier (PID) of the instrument, e.g.
742
+ "https://hdl.handle.net/21.12132/3.191564170f8a4686".
743
+ site_id: Site ID, e.g. "hyytiala".
744
+ username: Username for HTTP Basic authentication.
745
+ password: Password for HTTP Basic authentication.
746
+ tags: Optional tags to distinguish files with the same filename,
747
+ e.g. ["co"] and ["cross"] for Halo Doppler lidar files.
748
+
749
+ Raises:
750
+ FileNotFoundError: If the file does not exist.
751
+ CloudnetAPIError: If the upload fails.
752
+
753
+ Example:
754
+ >>> client = APIClient()
755
+ >>> client.submit(
756
+ ... "20250801_Magurele_CHM170137_000.nc",
757
+ ... date="2025-08-01",
758
+ ... instrument_id="chm15k",
759
+ ... instrument_pid="https://hdl.handle.net/21.12132/3.c60c931fac9d43f0",
760
+ ... site_id="bucharest",
761
+ ... username="example",
762
+ ... password="letmein",
763
+ ... )
764
+ """
765
+ path = Path(filename)
766
+ checksum = md5sum(path)
767
+ if not isinstance(date, datetime.date):
768
+ date = datetime.date.fromisoformat(date)
769
+ auth = (username, password)
770
+ upload_url = f"{self.base_url}upload/"
771
+ metadata: dict[str, Any] = {
772
+ "measurementDate": date.strftime("%Y-%m-%d"),
773
+ "instrument": instrument_id,
774
+ "instrumentPid": instrument_pid,
775
+ "filename": path.name,
776
+ "checksum": checksum,
777
+ "site": site_id,
778
+ }
779
+ if tags is not None:
780
+ metadata["tags"] = list(tags)
781
+ res = self.session.post(f"{upload_url}metadata/", json=metadata, auth=auth)
782
+ if res.status_code == 409:
783
+ logger.info(
784
+ "%s has already been submitted, skipping data upload", path.name
785
+ )
786
+ return
787
+ if res.status_code != 200:
788
+ raise CloudnetAPIError(_upload_error_message(res, "Metadata upload"))
789
+ logger.info("Uploading %s", path.name)
790
+ with path.open("rb") as f:
791
+ res = self.session.put(f"{upload_url}data/{checksum}", data=f, auth=auth)
792
+ if res.status_code not in (200, 201):
793
+ raise CloudnetAPIError(_upload_error_message(res, "Data upload"))
794
+ logger.info("Submitted %s", path.name)
795
+
708
796
  def download(
709
797
  self,
710
798
  metadata: MetadataList | TMetadata,
@@ -878,7 +966,7 @@ class APIClient:
878
966
  requests.exceptions.Timeout: If the request times out.
879
967
  """
880
968
  try:
881
- url = urljoin(self.base_url, endpoint)
969
+ url = f"{self.base_url}api/{endpoint}"
882
970
  res = self.session.get(url, params=params, timeout=120)
883
971
  res.raise_for_status()
884
972
  data = res.json()
@@ -892,6 +980,20 @@ class APIClient:
892
980
  raise
893
981
 
894
982
 
983
+ def _upload_error_message(res: requests.Response, stage: str) -> str:
984
+ """Build an error message from a failed upload response.
985
+
986
+ Args:
987
+ res: The failed upload response.
988
+ stage: Name of the upload stage, e.g. "Metadata upload".
989
+
990
+ Returns:
991
+ Error message including the HTTP status code and the server's
992
+ plaintext message.
993
+ """
994
+ return f"{stage} failed with HTTP {res.status_code}: {res.text}"
995
+
996
+
895
997
  def _add_date_params(
896
998
  params: dict,
897
999
  date: DateParam,
@@ -965,6 +1067,8 @@ def _parse_date_param(date: DateParam) -> tuple[datetime.date, datetime.date]:
965
1067
  Raises:
966
1068
  ValueError: If the date format is invalid.
967
1069
  """
1070
+ if isinstance(date, datetime.datetime):
1071
+ date = date.date()
968
1072
  if isinstance(date, datetime.date):
969
1073
  return date, date
970
1074
  error = ValueError(f"Invalid date format: {date}")
@@ -241,7 +241,7 @@ async def _download_file(
241
241
  aiohttp.ClientError: If the download fails.
242
242
  Exception: If file operations fail.
243
243
  """
244
- download_url = f"{params.base_url}{params.meta.download_url.split('/api/')[-1]}"
244
+ download_url = f"{params.base_url}api/{params.meta.download_url.split('/api/')[-1]}"
245
245
  hasher = (
246
246
  hashlib.sha256() if isinstance(params.meta, ProductMetadata) else hashlib.md5()
247
247
  )
@@ -287,7 +287,7 @@ async def _refresh_meta(params: DlParams) -> Metadata:
287
287
  else:
288
288
  msg = "Invalid metadata"
289
289
  raise ValueError(msg)
290
- url = f"{params.base_url}{endpoint}/{params.meta.uuid}"
290
+ url = f"{params.base_url}api/{endpoint}/{params.meta.uuid}"
291
291
  async with params.session.get(url) as res:
292
292
  res.raise_for_status()
293
293
  obj = await res.json()
@@ -1,3 +1,3 @@
1
1
  """Version information for the cloudnet-api-client package."""
2
2
 
3
- __version__ = "0.12.13"
3
+ __version__ = "0.12.14"
@@ -13,13 +13,14 @@ requires-python = ">=3.10"
13
13
  classifiers = [
14
14
  "Development Status :: 3 - Alpha",
15
15
  "Intended Audience :: Science/Research",
16
- "License :: OSI Approved :: MIT License",
17
16
  "Operating System :: OS Independent",
18
17
  "Programming Language :: Python :: 3",
19
18
  "Topic :: Scientific/Engineering :: Atmospheric Science",
20
19
  ]
21
20
  dependencies = ["aiohttp", "numpy", "requests", "tqdm"]
22
21
  dynamic = ["version"]
22
+ license = "MIT"
23
+ license-files = ["LICENSE"]
23
24
 
24
25
  [project.optional-dependencies]
25
26
  test = ["mypy", "netCDF4", "pytest", "pytest-asyncio"]
@@ -1,6 +1,7 @@
1
1
  import dataclasses
2
2
  import datetime
3
3
  import os
4
+ import shutil
4
5
  from pathlib import Path
5
6
  from typing import NamedTuple
6
7
  from uuid import UUID
@@ -591,6 +592,58 @@ class TestFilterCombinations:
591
592
  assert len(meta) == 2
592
593
 
593
594
 
595
+ class TestSubmit:
596
+ def test_submit_new_file(self, client: APIClient, data_path: Path, tmp_path: Path):
597
+ file_path = tmp_path / "20250903_JOYCE_WST_01m.dat"
598
+ shutil.copy(data_path / "20250803_JOYCE_WST_01m.dat", file_path)
599
+ with file_path.open("ab") as f:
600
+ f.write(b"\n")
601
+ client.submit(
602
+ file_path,
603
+ date="2025-09-03",
604
+ instrument_id="weather-station",
605
+ instrument_pid=JUELICH_WST_PID,
606
+ site_id="juelich",
607
+ username="admin",
608
+ password="admin",
609
+ )
610
+ meta = client.raw_files(site_id="juelich", date="2025-09-03")
611
+ assert len(meta) == 1
612
+ assert meta[0].filename == file_path.name
613
+ assert meta[0].instrument.instrument_id == "weather-station"
614
+
615
+ def test_submit_existing_file_is_noop(self, client: APIClient, data_path: Path):
616
+ # This file was already submitted by the submit_raw_files fixture,
617
+ # so the server responds 409 and the data upload must be skipped.
618
+ client.submit(
619
+ data_path / "20250801_Magurele_CHM170137_000.nc",
620
+ date="2025-08-01",
621
+ instrument_id="chm15k",
622
+ instrument_pid=BUCHAREST_CHM15K_PID,
623
+ site_id="bucharest",
624
+ username="admin",
625
+ password="admin",
626
+ )
627
+ meta = client.raw_files(site_id="bucharest", date="2025-08-01")
628
+ assert len(meta) == 1
629
+
630
+ def test_submit_with_invalid_credentials(
631
+ self, client: APIClient, data_path: Path, tmp_path: Path
632
+ ):
633
+ file_path = tmp_path / "20250904_JOYCE_WST_01m.dat"
634
+ shutil.copy(data_path / "20250803_JOYCE_WST_01m.dat", file_path)
635
+ with pytest.raises(CloudnetAPIError):
636
+ client.submit(
637
+ file_path,
638
+ date="2025-09-04",
639
+ instrument_id="weather-station",
640
+ instrument_pid=JUELICH_WST_PID,
641
+ site_id="juelich",
642
+ username="admin",
643
+ password="wrong-password",
644
+ )
645
+
646
+
594
647
  def test_get_instrument_derived_products(client: APIClient):
595
648
  assert client.instrument_derived_products("hatpro") == {"mwr", "mwr-l1c"}
596
649
  assert client.instrument_derived_products("pluvio") == {"rain-gauge"}