cropwise-api-client 0.1.7__tar.gz → 0.1.8__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.
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/PKG-INFO +1 -1
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/README.ru.md +1 -1
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/cropwise/client.py +190 -8
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/pyproject.toml +1 -1
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/.github/workflows/publish.yml +0 -0
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/.gitignore +0 -0
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/README.md +0 -0
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/cropwise/__init__.py +0 -0
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/cropwise/exceptions.py +0 -0
- {cropwise_api_client-0.1.7 → cropwise_api_client-0.1.8}/cropwise/processing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: cropwise-api-client
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.8
|
|
4
4
|
Summary: A Python client library for the Cropwise Operations API v3 with spatial GIS capabilities.
|
|
5
5
|
Project-URL: Homepage, https://github.com/CzendaZdenda/cropwise-api-client
|
|
6
6
|
Project-URL: Bug-Tracker, https://github.com/CzendaZdenda/cropwise-api-client
|
|
@@ -135,7 +135,7 @@ from cropwise import CropwiseClient
|
|
|
135
135
|
|
|
136
136
|
client = CropwiseClient(token="your_token")
|
|
137
137
|
|
|
138
|
-
# Получение дополнительных объектов с типом "
|
|
138
|
+
# Получение дополнительных объектов с типом "временные дороги"
|
|
139
139
|
objects_df = client.get_additional_objects(object_type="временные дороги").set_index('id')
|
|
140
140
|
|
|
141
141
|
# Удаление объектов с сервера
|
|
@@ -15,14 +15,39 @@ logger = logging.getLogger("cropwise")
|
|
|
15
15
|
|
|
16
16
|
# Standard Cropwise API response status mapping
|
|
17
17
|
RESPONSE_STATUS = {
|
|
18
|
-
400: (
|
|
19
|
-
|
|
18
|
+
400: (
|
|
19
|
+
'Bad Request',
|
|
20
|
+
'The request could not be understood or was missing required parameters.',
|
|
21
|
+
),
|
|
22
|
+
401: (
|
|
23
|
+
'Unauthorized',
|
|
24
|
+
(
|
|
25
|
+
"Authentication failed or user doesn't have permissions for"
|
|
26
|
+
' requested operation.'
|
|
27
|
+
),
|
|
28
|
+
),
|
|
20
29
|
403: ('Forbidden', 'Access denied.'),
|
|
21
30
|
404: ('Not Found', 'Resource was not found.'),
|
|
22
|
-
|
|
23
|
-
|
|
31
|
+
413: (
|
|
32
|
+
'Payload Too Large',
|
|
33
|
+
'Request URI or query parameters exceed server limits.',
|
|
34
|
+
),
|
|
35
|
+
414: ('URI Too Long', 'Request URI exceeds server limits.'),
|
|
36
|
+
422: (
|
|
37
|
+
'Unprocessable Entity',
|
|
38
|
+
'The request was well-formed but failed due to semantic errors.',
|
|
39
|
+
),
|
|
40
|
+
503: (
|
|
41
|
+
'Service Unavailable',
|
|
42
|
+
(
|
|
43
|
+
'Service is temporarily unavailable (e.g. scheduled Platform'
|
|
44
|
+
' Maintenance).'
|
|
45
|
+
),
|
|
46
|
+
),
|
|
24
47
|
}
|
|
25
48
|
|
|
49
|
+
# Safe character limit for a single comma-separated list parameter (~200-250 IDs)
|
|
50
|
+
MAX_QUERY_PARAM_LENGTH = 2000
|
|
26
51
|
|
|
27
52
|
class CropwiseClient:
|
|
28
53
|
def __init__(
|
|
@@ -186,11 +211,108 @@ class CropwiseClient:
|
|
|
186
211
|
|
|
187
212
|
return df
|
|
188
213
|
|
|
189
|
-
def
|
|
190
|
-
|
|
214
|
+
def _split_list_filters(
|
|
215
|
+
self, kwargs: Dict[str, Any], max_param_len: int = MAX_QUERY_PARAM_LENGTH
|
|
216
|
+
) -> List[Dict[str, Any]]:
|
|
217
|
+
"""
|
|
218
|
+
Splits kwargs into a list of independent filter dictionaries if any list-like
|
|
219
|
+
parameter (list/tuple/set) exceeds max_param_len when serialized.
|
|
220
|
+
"""
|
|
221
|
+
# Find the first list-like parameter that exceeds the length threshold
|
|
222
|
+
for key, val in kwargs.items():
|
|
223
|
+
if isinstance(val, (list, tuple, set)):
|
|
224
|
+
# Preserve order while deduplicating IDs
|
|
225
|
+
items = list(dict.fromkeys(val))
|
|
226
|
+
if not items:
|
|
227
|
+
continue
|
|
228
|
+
|
|
229
|
+
# Check the total serialized length of "id1,id2,..."
|
|
230
|
+
if len(','.join(str(x) for x in items)) > max_param_len:
|
|
231
|
+
chunks = []
|
|
232
|
+
current_batch = []
|
|
233
|
+
current_len = 0
|
|
234
|
+
|
|
235
|
+
for item in items:
|
|
236
|
+
item_str = str(item)
|
|
237
|
+
# Account for +1 character for the comma separator
|
|
238
|
+
added_len = len(item_str) + (1 if current_batch else 0)
|
|
239
|
+
if current_batch and (current_len + added_len > max_param_len):
|
|
240
|
+
batch_kwargs = kwargs.copy()
|
|
241
|
+
batch_kwargs[key] = current_batch
|
|
242
|
+
# Recursively check remaining parameters in case multiple large lists exist
|
|
243
|
+
chunks.extend(self._split_list_filters(batch_kwargs, max_param_len))
|
|
244
|
+
current_batch = [item]
|
|
245
|
+
current_len = len(item_str)
|
|
246
|
+
else:
|
|
247
|
+
current_batch.append(item)
|
|
248
|
+
current_len += added_len
|
|
249
|
+
|
|
250
|
+
if current_batch:
|
|
251
|
+
batch_kwargs = kwargs.copy()
|
|
252
|
+
batch_kwargs[key] = current_batch
|
|
253
|
+
chunks.extend(self._split_list_filters(batch_kwargs, max_param_len))
|
|
254
|
+
|
|
255
|
+
return chunks
|
|
256
|
+
|
|
257
|
+
return [kwargs]
|
|
258
|
+
|
|
259
|
+
def _fetch_single_or_split(self, endpoint: str, kwargs: dict) -> List[Dict[str, Any]]:
|
|
260
|
+
"""
|
|
261
|
+
Executes _get_all_pages and automatically bisects the longest list filter
|
|
262
|
+
upon receiving HTTP 413/414, retrying the sub-batches recursively.
|
|
263
|
+
"""
|
|
191
264
|
filters = self._prepare_filters(kwargs)
|
|
192
|
-
|
|
193
|
-
|
|
265
|
+
try:
|
|
266
|
+
return self._get_all_pages(endpoint, filter_params=filters)
|
|
267
|
+
except CropwiseApiException as e:
|
|
268
|
+
if "HTTP 413" not in str(e) and "HTTP 414" not in str(e):
|
|
269
|
+
raise
|
|
270
|
+
|
|
271
|
+
# Identify the longest list-like filter in kwargs that can still be split
|
|
272
|
+
longest_key = None
|
|
273
|
+
longest_len = 1
|
|
274
|
+
for k, v in kwargs.items():
|
|
275
|
+
if isinstance(v, (list, tuple, set)) and len(v) > longest_len:
|
|
276
|
+
longest_key = k
|
|
277
|
+
longest_len = len(v)
|
|
278
|
+
|
|
279
|
+
if longest_key is None:
|
|
280
|
+
raise
|
|
281
|
+
|
|
282
|
+
seq = list(kwargs[longest_key])
|
|
283
|
+
mid = len(seq) // 2
|
|
284
|
+
logger.warning(
|
|
285
|
+
f"HTTP 413/414 on '{endpoint}'. Splitting '{longest_key}' "
|
|
286
|
+
f"({len(seq)} items) into {mid} and {len(seq) - mid}..."
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
left_kwargs = {**kwargs, longest_key: seq[:mid]}
|
|
290
|
+
right_kwargs = {**kwargs, longest_key: seq[mid:]}
|
|
291
|
+
|
|
292
|
+
return (
|
|
293
|
+
self._fetch_single_or_split(endpoint, left_kwargs)
|
|
294
|
+
+ self._fetch_single_or_split(endpoint, right_kwargs)
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
def _request_and_parse(self, endpoint: str, kwargs: dict) -> pd.DataFrame:
|
|
298
|
+
"""Internal helper to process filters, auto-chunk large ID lists, fetch all pages, and return a DataFrame."""
|
|
299
|
+
batches = self._split_list_filters(kwargs)
|
|
300
|
+
|
|
301
|
+
if len(batches) > 1:
|
|
302
|
+
logger.info(f"Query for '{endpoint}' split into {len(batches)} chunks to avoid URI length limits.")
|
|
303
|
+
|
|
304
|
+
all_data: List[Dict[str, Any]] = []
|
|
305
|
+
for batch_kwargs in batches:
|
|
306
|
+
all_data.extend(self._fetch_single_or_split(endpoint, batch_kwargs))
|
|
307
|
+
|
|
308
|
+
# Pass only 'sort_by' to _to_dataframe to preserve default sorting behavior
|
|
309
|
+
df = self._to_dataframe(all_data, self._prepare_filters({'sort_by': kwargs.get('sort_by')}))
|
|
310
|
+
|
|
311
|
+
# Safeguard against duplicate records across batch boundaries
|
|
312
|
+
if not df.empty and 'id' in df.columns:
|
|
313
|
+
df = df.drop_duplicates(subset=['id'])
|
|
314
|
+
|
|
315
|
+
return df
|
|
194
316
|
|
|
195
317
|
def _send_mutation(self, method: str, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
196
318
|
"""
|
|
@@ -226,6 +348,36 @@ class CropwiseClient:
|
|
|
226
348
|
"""
|
|
227
349
|
return self._request_and_parse('fields', kwargs)
|
|
228
350
|
|
|
351
|
+
def get_field_groups(self, **kwargs) -> pd.DataFrame:
|
|
352
|
+
"""
|
|
353
|
+
Fetches field groups with optional filters.
|
|
354
|
+
|
|
355
|
+
Exact match:
|
|
356
|
+
id, name, group_folder_id, description, administrative_area_name, subadministrative_area_name, locality, external_id, hidden
|
|
357
|
+
|
|
358
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
359
|
+
created_at, updated_at
|
|
360
|
+
|
|
361
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
362
|
+
id, created_at, updated_at
|
|
363
|
+
"""
|
|
364
|
+
return self._request_and_parse('field_groups', kwargs)
|
|
365
|
+
|
|
366
|
+
def get_group_folders(self, **kwargs) -> pd.DataFrame:
|
|
367
|
+
"""
|
|
368
|
+
Fetches group folders with optional filters.
|
|
369
|
+
|
|
370
|
+
Exact match:
|
|
371
|
+
id, name, hidden, external_id, cwp_type, cwp_id
|
|
372
|
+
|
|
373
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
374
|
+
created_at, updated_at
|
|
375
|
+
|
|
376
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
377
|
+
id, created_at, updated_at
|
|
378
|
+
"""
|
|
379
|
+
return self._request_and_parse('group_folders', kwargs)
|
|
380
|
+
|
|
229
381
|
def get_machines(self, **kwargs) -> pd.DataFrame:
|
|
230
382
|
"""
|
|
231
383
|
Fetches all registered agricultural machinery.
|
|
@@ -293,6 +445,36 @@ class CropwiseClient:
|
|
|
293
445
|
"""
|
|
294
446
|
return self._request_and_parse('machine_groups', kwargs)
|
|
295
447
|
|
|
448
|
+
def get_machine_regions(self, **kwargs) -> pd.DataFrame:
|
|
449
|
+
"""
|
|
450
|
+
Fetches machine regions with optional filters.
|
|
451
|
+
|
|
452
|
+
Exact match:
|
|
453
|
+
id, name, ancestry, hidden, external_id
|
|
454
|
+
|
|
455
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
456
|
+
created_at, updated_at
|
|
457
|
+
|
|
458
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
459
|
+
id, created_at, updated_at
|
|
460
|
+
"""
|
|
461
|
+
return self._request_and_parse('machine_regions', kwargs)
|
|
462
|
+
|
|
463
|
+
def get_machine_region_mapping_items(self, **kwargs) -> pd.DataFrame:
|
|
464
|
+
"""
|
|
465
|
+
Fetches mapping links between machines and regions.
|
|
466
|
+
|
|
467
|
+
Exact match:
|
|
468
|
+
id, machine_id, machine_region_id, date_start, date_end, no_date_end
|
|
469
|
+
|
|
470
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
471
|
+
date_start, date_end, created_at, updated_at
|
|
472
|
+
|
|
473
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
474
|
+
id, created_at, updated_at
|
|
475
|
+
"""
|
|
476
|
+
return self._request_and_parse('machine_region_mapping_items', kwargs)
|
|
477
|
+
|
|
296
478
|
def get_implements(self, **kwargs) -> pd.DataFrame:
|
|
297
479
|
"""
|
|
298
480
|
Fetches attached agricultural implements with optional filters.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "cropwise-api-client"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.8"
|
|
8
8
|
description = "A Python client library for the Cropwise Operations API v3 with spatial GIS capabilities."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|