pixel-client 1.2.1__tar.gz → 1.2.3__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pixel-client
3
- Version: 1.2.1
3
+ Version: 1.2.3
4
4
  Summary: Client library for Geodata Pixel
5
5
  Project-URL: Documentation, https://doc.geodatapixel.no/
6
6
  Project-URL: Organization, https://geodata.no
@@ -15,6 +15,7 @@ Requires-Dist: httpx>=0.28.1
15
15
  Requires-Dist: packaging>=25.0
16
16
  Requires-Dist: pydantic-settings>=2.8.0
17
17
  Requires-Dist: pydantic[email]>=2.10.6
18
+ Requires-Dist: tenacity>=9.1.2
18
19
  Requires-Dist: tqdm>=4.67.1
19
20
  Description-Content-Type: text/markdown
20
21
 
@@ -63,12 +64,9 @@ client = get_client()
63
64
 
64
65
  # Using direct settings
65
66
  settings = PixelApiSettings(
66
- PIXEL_API_URL="your_api_url",
67
- KEYCLOAK_SERVER_URL="your_keycloak_server_url",
68
- KEYCLOAK_CLIENT_ID="your_client_id",
69
- KEYCLOAK_REALM="your_realm",
70
- KEYCLOAK_USERNAME="your_username",
71
- KEYCLOAK_PASSWORD="your_password"
67
+ PIXEL_TENANT="your_realm",
68
+ PIXEL_USERNAME="your_username",
69
+ PIXEL_PASSWORD="your_password"
72
70
  )
73
71
  client = get_client(settings=settings)
74
72
 
@@ -43,12 +43,9 @@ client = get_client()
43
43
 
44
44
  # Using direct settings
45
45
  settings = PixelApiSettings(
46
- PIXEL_API_URL="your_api_url",
47
- KEYCLOAK_SERVER_URL="your_keycloak_server_url",
48
- KEYCLOAK_CLIENT_ID="your_client_id",
49
- KEYCLOAK_REALM="your_realm",
50
- KEYCLOAK_USERNAME="your_username",
51
- KEYCLOAK_PASSWORD="your_password"
46
+ PIXEL_TENANT="your_realm",
47
+ PIXEL_USERNAME="your_username",
48
+ PIXEL_PASSWORD="your_password"
52
49
  )
53
50
  client = get_client(settings=settings)
54
51
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pixel-client"
3
- version = "1.2.1"
3
+ version = "1.2.3"
4
4
  description = "Client library for Geodata Pixel"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -24,6 +24,7 @@ dependencies = [
24
24
  "pydantic-settings>=2.8.0",
25
25
  "tqdm>=4.67.1",
26
26
  "packaging>=25.0",
27
+ "tenacity>=9.1.2",
27
28
  ]
28
29
 
29
30
  [project.urls]
@@ -57,3 +58,8 @@ docs = [
57
58
  include = [
58
59
  "src/*"
59
60
  ]
61
+
62
+
63
+ [tool.basedpyright]
64
+ include = ["src"]
65
+ typeCheckingMode = "basic"
@@ -5,10 +5,12 @@ from functools import partial
5
5
  from pathlib import Path
6
6
  from typing import Any, AsyncGenerator, Literal, TypeVar, Self, TypedDict, Unpack
7
7
  from uuid import uuid4
8
-
8
+ import tenacity
9
9
  import httpx
10
10
  from geojson_pydantic import Polygon
11
- from tqdm import tqdm
11
+ import tqdm
12
+ from tqdm.asyncio import tqdm_asyncio
13
+
12
14
 
13
15
  from .auth import KeyCloakAuth
14
16
  from .exceptions import (
@@ -53,10 +55,13 @@ DEFAULT_PIXEL_TIMEOUT = httpx.Timeout(
53
55
  write=15.0,
54
56
  )
55
57
  DEFAULT_UPLOAD_TIMEOUT = httpx.Timeout(
56
- 10.0,
58
+ 30.0,
57
59
  write=300.0, # Increased write timeout for uploads
58
60
  )
59
61
 
62
+ DEFAULT_UPLOAD_RETRIES = 8
63
+ DEFAULT_MAX_CONCURRENCY = 10 # Maximum number of concurrent uploads
64
+
60
65
 
61
66
  class PixelClientKwargs(TypedDict, total=False):
62
67
  """TypedDict for PixelClient constructor arguments."""
@@ -67,6 +72,12 @@ class PixelClientKwargs(TypedDict, total=False):
67
72
  timeout_upload: httpx.Timeout
68
73
  """Timeout configuration for file uploads. Defaults to DEFAULT_UPLOAD_TIMEOUT"""
69
74
 
75
+ upload_num_retries: int
76
+ """Number of retries for upload operations. Defaults to DEFAULT_UPLOAD_RETRIES."""
77
+
78
+ upload_max_concurrency: int
79
+ """Maximum number of concurrent uploads. Defaults to 10."""
80
+
70
81
 
71
82
  class PixelClientAsync:
72
83
  """Asynchronous client for interacting with the Pixel API.
@@ -86,6 +97,8 @@ class PixelClientAsync:
86
97
  password: str,
87
98
  timeout_pixel: httpx.Timeout = DEFAULT_PIXEL_TIMEOUT,
88
99
  timeout_upload: httpx.Timeout = DEFAULT_UPLOAD_TIMEOUT,
100
+ upload_num_retries: int = DEFAULT_UPLOAD_RETRIES,
101
+ upload_max_concurrency: int = DEFAULT_MAX_CONCURRENCY,
89
102
  ):
90
103
  """Initialize a new Pixel API client.
91
104
 
@@ -111,6 +124,17 @@ class PixelClientAsync:
111
124
  self._internal_client = httpx.AsyncClient(
112
125
  timeout=self._timeout_upload, # Use a separate client for uploads
113
126
  ) # For s3 uploads
127
+ self._semaphore: asyncio.Semaphore = asyncio.Semaphore(upload_max_concurrency)
128
+
129
+ self._retry_policy = tenacity.AsyncRetrying(
130
+ stop=tenacity.stop_after_attempt(upload_num_retries),
131
+ wait=tenacity.wait_random_exponential(),
132
+ before=tenacity.before_log(logger, logging.DEBUG),
133
+ after=tenacity.after_log(logger, logging.DEBUG),
134
+ )
135
+ self._internal_client.request = self._retry_policy.wraps(
136
+ self._internal_client.request
137
+ )
114
138
 
115
139
  @classmethod
116
140
  def from_settings(
@@ -127,11 +151,11 @@ class PixelClientAsync:
127
151
  """
128
152
  return cls(
129
153
  url=settings.PIXEL_API_URL,
130
- keycloak_server_url=settings.KEYCLOAK_SERVER_URL,
131
- client_id=settings.KEYCLOAK_CLIENT_ID,
132
- username=settings.KEYCLOAK_USERNAME,
133
- password=settings.KEYCLOAK_PASSWORD.get_secret_value(),
134
- realm=settings.KEYCLOAK_REALM.get_secret_value(),
154
+ keycloak_server_url=settings.PIXEL_SERVER_URL,
155
+ client_id=settings.PIXEL_CLIENT_ID,
156
+ username=settings.PIXEL_USERNAME,
157
+ password=settings.PIXEL_PASSWORD.get_secret_value(),
158
+ realm=settings.PIXEL_REALM,
135
159
  **kwargs,
136
160
  )
137
161
 
@@ -1099,61 +1123,43 @@ class PixelClientAsync:
1099
1123
  Raises:
1100
1124
  httpx.HTTPStatusError: If the upload fails.
1101
1125
  """
1102
- response = await self._internal_client.post(
1103
- upload_job["url"],
1104
- files={"file": file_path.read_bytes()},
1105
- data=upload_job["upload_fields"],
1106
- )
1107
- response.raise_for_status()
1108
- return None
1109
-
1110
- async def _upload_part_to_s3(
1111
- self,
1112
- part: dict,
1113
- part_data: bytes,
1114
- ):
1115
- """Upload a part of a file to S3 as part of a multipart upload.
1116
-
1117
- Args:
1118
- part: Part object containing the S3 URL and headers.
1119
- part_data: Binary data for this part of the file.
1120
-
1121
- Returns:
1122
- None: This method returns None on success.
1123
-
1124
- Raises:
1125
- httpx.HTTPStatusError: If the upload fails.
1126
- """
1127
- response = await self._internal_client.put(
1128
- part["url"], content=part_data, headers=part["headers"]
1129
- )
1130
- response.raise_for_status()
1126
+ async with self._semaphore:
1127
+ response = await self._internal_client.post(
1128
+ upload_job["url"],
1129
+ files={"file": file_path.read_bytes()},
1130
+ data=upload_job["upload_fields"],
1131
+ )
1132
+ response.raise_for_status()
1131
1133
  return None
1132
1134
 
1133
- async def _upload_multipart_to_s3(
1134
- self,
1135
- upload_job: dict,
1136
- file_path: Path,
1137
- multipart_part_size: int,
1138
- ):
1139
- """Upload all parts of a file to S3 using a multipart upload.
1140
1135
 
1141
- Args:
1142
- upload_job: Upload job object containing the parts information.
1143
- file_path: Path to the file to upload.
1144
- multipart_part_size: Size of each part in bytes.
1145
-
1146
- Returns:
1147
- None: This method returns None on success.
1148
- """
1136
+ async def _upload_multipart_to_s3(self, upload_job: dict, file_path: Path, multipart_part_size: int):
1149
1137
  parts = sorted(upload_job["upload_parts"], key=lambda p: p["part_number"])
1150
- upload_iterator = zip(iter_file_parts(file_path, multipart_part_size), parts)
1151
- await asyncio.gather(
1152
- *[
1153
- self._upload_part_to_s3(part, part_data)
1154
- for (_, _, part_data), part in upload_iterator
1155
- ]
1156
- )
1138
+
1139
+
1140
+ async def read_and_upload_single_part(part_index, part):
1141
+
1142
+ async with self._semaphore:
1143
+ with open(file_path, 'rb') as f:
1144
+ f.seek(part_index * multipart_part_size)
1145
+ part_data = f.read(multipart_part_size)
1146
+
1147
+ response = await self._internal_client.put(
1148
+ part["url"], content=part_data, headers=part["headers"]
1149
+ )
1150
+ response.raise_for_status()
1151
+
1152
+
1153
+
1154
+ tasks = [
1155
+ read_and_upload_single_part(i, part)
1156
+ for i, part in enumerate(parts)
1157
+ ]
1158
+
1159
+ with silence_logger(logging.getLogger("httpx")):
1160
+ await tqdm_asyncio.gather(*tasks, total=len(tasks),
1161
+ desc=f"Uploading {file_path.name} to Pixel")
1162
+
1157
1163
  return None
1158
1164
 
1159
1165
  async def _upload_to_s3(
@@ -1888,7 +1894,7 @@ class PixelClientAsync:
1888
1894
  num_jobs = job["total_jobs"]
1889
1895
  with (
1890
1896
  silence_logger(logging.getLogger("httpx")),
1891
- tqdm(total=num_jobs, desc=f"Running group job {group_job_id}") as pbar,
1897
+ tqdm.tqdm(total=num_jobs, desc=f"Running group job {group_job_id}") as pbar,
1892
1898
  ):
1893
1899
  while not job["completed"]:
1894
1900
  job = await self.get_job_group(group_job_id)
@@ -0,0 +1,63 @@
1
+ from pathlib import Path
2
+ from typing import Literal
3
+
4
+ from pydantic import SecretStr, Field, AliasChoices
5
+ from pydantic_settings import BaseSettings, SettingsConfigDict
6
+
7
+
8
+ pixel_env_choices = AliasChoices("PIXEL_ENV", "KEYCLOAK_ENV")
9
+ pixel_username_choices = AliasChoices("PIXEL_USERNAME", "KEYCLOAK_USERNAME")
10
+ pixel_password_choices = AliasChoices("PIXEL_PASSWORD", "KEYCLOAK_PASSWORD")
11
+ pixel_realm_choices = AliasChoices("PIXEL_TENANT", "KEYCLOAK_REALM")
12
+
13
+ class PixelApiSettings(BaseSettings):
14
+ """
15
+ Settings for the Pixel API client
16
+ """
17
+
18
+ @classmethod
19
+ def from_env_file(cls, env_file: Path | str) -> "PixelApiSettings":
20
+ """Instantiate the settings from an environment file.
21
+
22
+ Warning:
23
+ Environment variables will always take precedence over the values in the file.
24
+ """
25
+ return cls(_env_file=env_file) # type: ignore
26
+
27
+ model_config = SettingsConfigDict(frozen=True, extra="ignore") # Makes it hashable
28
+
29
+
30
+
31
+ PIXEL_ENV: Literal["dev", "test", "prod"] = Field(validation_alias=pixel_env_choices, default="prod")
32
+
33
+ PIXEL_USERNAME: str = Field(validation_alias=pixel_username_choices)
34
+ """The client secret for the Keycloak server"""
35
+
36
+ PIXEL_PASSWORD: SecretStr = Field(validation_alias=pixel_password_choices)
37
+ """The password for the Keycloak"""
38
+
39
+ PIXEL_TENANT: str = Field(validation_alias=pixel_realm_choices)
40
+ """The realm for the Keycloak server"""
41
+
42
+ PIXEL_SERVER_URL_OVERRIDE: str | None = Field(alias="PIXEL_SERVER_URL", default=None)
43
+ PIXEL_API_URL_OVERRIDE: str | None = Field(alias="PIXEL_API_URL", default=None)
44
+
45
+ @property
46
+ def PIXEL_CLIENT_ID(self):
47
+ return "frontend"
48
+
49
+
50
+ @property
51
+ def PIXEL_REALM(self):
52
+ return self.PIXEL_TENANT.capitalize()
53
+
54
+ @property
55
+ def PIXEL_API_URL(self):
56
+ return self.PIXEL_API_URL_OVERRIDE or f"https://{self.PIXEL_ENV}.api.geodatapixel.no/{self.PIXEL_REALM.lower()}"
57
+
58
+ @property
59
+ def PIXEL_SERVER_URL(self):
60
+ return self.PIXEL_SERVER_URL_OVERRIDE or f"https://{self.PIXEL_ENV}.keycloak.geodatapixel.no"
61
+
62
+ PIXEL_CLIENT_NO_VERSION_CHECK: bool = False
63
+ """If True, the client will not check for a newer version of the pixel-client package on startup."""
@@ -1,42 +0,0 @@
1
- from pathlib import Path
2
-
3
- from pydantic import SecretStr
4
- from pydantic_settings import BaseSettings, SettingsConfigDict
5
-
6
-
7
- class PixelApiSettings(BaseSettings):
8
- """
9
- Settings for the Pixel API client
10
- """
11
-
12
- @classmethod
13
- def from_env_file(cls, env_file: Path | str) -> "PixelApiSettings":
14
- """Instantiate the settings from an environment file.
15
-
16
- Warning:
17
- Environment variables will always take precedence over the values in the file.
18
- """
19
- return cls(_env_file=env_file) # type: ignore
20
-
21
- model_config = SettingsConfigDict(frozen=True) # Makes it hashable
22
-
23
- PIXEL_API_URL: str
24
- """The URL of the Pixel API"""
25
-
26
- KEYCLOAK_SERVER_URL: str
27
- """The URL for the Keycloak server"""
28
-
29
- KEYCLOAK_CLIENT_ID: str = "frontend"
30
- """The client ID for the Keycloak server"""
31
-
32
- KEYCLOAK_USERNAME: str
33
- """The client secret for the Keycloak server"""
34
-
35
- KEYCLOAK_PASSWORD: SecretStr
36
- """The password for the Keycloak"""
37
-
38
- KEYCLOAK_REALM: SecretStr
39
- """The realm for the Keycloak server"""
40
-
41
- PIXEL_CLIENT_NO_VERSION_CHECK: bool = False
42
- """If True, the client will not check for a newer version of the pixel-client package on startup."""
File without changes
File without changes