gzw-data 0.1.1__py3-none-any.whl

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.
gzw_data/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Python client for the free Gray Zone Warfare data API (https://gzw-data.dev)."""
2
+
3
+ from .client import GzwApiError, GzwDataClient
4
+
5
+ __all__ = ["GzwApiError", "GzwDataClient"]
6
+ __version__ = "0.1.1"
gzw_data/client.py ADDED
@@ -0,0 +1,126 @@
1
+ """Small, dependency-free client built on urllib."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from typing import Any, Callable, Iterator, Optional
11
+
12
+ DEFAULT_BASE_URL = "https://gzw-data.dev/api/v1"
13
+ RETRYABLE_STATUS = {429, 500, 502, 503, 504}
14
+
15
+
16
+ class GzwApiError(Exception):
17
+ """Raised when the API returns an error or cannot be reached."""
18
+
19
+ def __init__(
20
+ self, message: str, *, status: int = 0, code: str = "UNKNOWN", url: str = "", retry_after: Optional[float] = None
21
+ ) -> None:
22
+ super().__init__(message)
23
+ self.status = status
24
+ self.code = code
25
+ self.url = url
26
+ self.retry_after = retry_after # seconds, from the Retry-After header when present
27
+
28
+
29
+ class GzwDataClient:
30
+ """Read-only client. No API key is needed.
31
+
32
+ >>> client = GzwDataClient()
33
+ >>> client.get("weapons", "ak-12")["name"]
34
+ 'AK-12'
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ base_url: str = DEFAULT_BASE_URL,
40
+ *,
41
+ timeout: float = 10.0,
42
+ retries: int = 2,
43
+ user_agent: str = "gzw-data-python/0.1.1",
44
+ max_retry_wait: float = 65.0,
45
+ opener: Optional[Callable[..., Any]] = None,
46
+ ) -> None:
47
+ self.base_url = base_url.rstrip("/")
48
+ self.timeout = timeout
49
+ self.retries = retries
50
+ self.user_agent = user_agent
51
+ self.max_retry_wait = max_retry_wait
52
+ self._open = opener or urllib.request.urlopen
53
+
54
+ # -- low level ---------------------------------------------------------
55
+
56
+ def request(self, path: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
57
+ """GET a path and return the full JSON envelope."""
58
+ query = urllib.parse.urlencode({k: v for k, v in (params or {}).items() if v is not None})
59
+ url = f"{self.base_url}/{path.lstrip('/')}" + (f"?{query}" if query else "")
60
+ req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": self.user_agent})
61
+ last: Optional[GzwApiError] = None
62
+ for attempt in range(self.retries + 1):
63
+ try:
64
+ with self._open(req, timeout=self.timeout) as response:
65
+ return json.loads(response.read().decode("utf-8"))
66
+ except urllib.error.HTTPError as exc:
67
+ last = self._from_http_error(exc, url)
68
+ if exc.code not in RETRYABLE_STATUS:
69
+ raise last from None
70
+ except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
71
+ last = GzwApiError(f"Request failed: {exc}", code="NETWORK_ERROR", url=url)
72
+ if attempt < self.retries:
73
+ delay = last.retry_after if last.retry_after is not None else min(0.4 * 2**attempt, 4.0)
74
+ time.sleep(min(delay, self.max_retry_wait))
75
+ assert last is not None
76
+ raise last
77
+
78
+ @staticmethod
79
+ def _from_http_error(exc: urllib.error.HTTPError, url: str) -> GzwApiError:
80
+ code, message = "HTTP_ERROR", f"HTTP {exc.code}"
81
+ retry_after: Optional[float] = None
82
+ try:
83
+ retry_after = float(exc.headers.get("Retry-After")) if exc.headers and exc.headers.get("Retry-After") else None
84
+ except (TypeError, ValueError):
85
+ pass
86
+ try:
87
+ error = json.loads(exc.read().decode("utf-8")).get("error", {})
88
+ code = error.get("code", code)
89
+ message = error.get("message", message)
90
+ except (ValueError, AttributeError):
91
+ pass
92
+ return GzwApiError(message, status=exc.code, code=code, url=url, retry_after=retry_after)
93
+
94
+ # -- API ---------------------------------------------------------------
95
+
96
+ def datasets(self) -> dict[str, int]:
97
+ """Dataset name -> record count."""
98
+ stats = self.request("stats")["data"]
99
+ return {name: int(info.get("total", 0)) for name, info in stats.items()}
100
+
101
+ def list(self, dataset: str, *, page: int = 1, per_page: int = 50, search: Optional[str] = None, **filters: Any) -> dict[str, Any]:
102
+ """One page of a dataset. Returns the envelope (``data``, ``total``, ``totalPages`` ...)."""
103
+ return self.request(dataset, {"page": page, "per_page": per_page, "search": search, **filters})
104
+
105
+ def iterate(self, dataset: str, *, per_page: int = 100, search: Optional[str] = None, **filters: Any) -> Iterator[dict[str, Any]]:
106
+ """Yield every record of a dataset, following pagination."""
107
+ page = 1
108
+ while True:
109
+ payload = self.list(dataset, page=page, per_page=per_page, search=search, **filters)
110
+ yield from payload["data"]
111
+ if page >= int(payload.get("totalPages", 1)) or not payload["data"]:
112
+ return
113
+ page += 1
114
+
115
+ def get(self, dataset: str, record_id: str) -> Optional[dict[str, Any]]:
116
+ """One record by id, or ``None`` if it does not exist."""
117
+ try:
118
+ return self.request(f"{dataset}/{urllib.parse.quote(record_id, safe='')}")["data"]
119
+ except GzwApiError as exc:
120
+ if exc.code == "RECORD_NOT_FOUND":
121
+ return None
122
+ raise
123
+
124
+ def search(self, query: str) -> dict[str, list[dict[str, Any]]]:
125
+ """Search all datasets. Returns dataset name -> matching records."""
126
+ return self.request("search", {"q": query})["data"]["results"]
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: gzw-data
3
+ Version: 0.1.1
4
+ Summary: Python client for the free Gray Zone Warfare data API (gzw-data.dev)
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://gzw-data.dev/
7
+ Project-URL: Source, https://github.com/ZoniBoy00/gzw-data-py
8
+ Keywords: gray-zone-warfare,gzw,api,game-data
9
+ Requires-Python: >=3.9
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # gzw-data (Python)
15
+
16
+ Dependency-free Python client for the free [Gray Zone Warfare data API](https://gzw-data.dev). Fan-made and not affiliated with the game's developer.
17
+
18
+ ```bash
19
+ pip install git+https://github.com/ZoniBoy00/gzw-data-py
20
+ ```
21
+
22
+ ```python
23
+ from gzw_data import GzwDataClient
24
+
25
+ client = GzwDataClient() # no API key needed
26
+ print(client.datasets()) # {'ammo': 79, 'weapons': 44, ...}
27
+ print(client.get("weapons", "ak-12")["name"]) # AK-12
28
+ for ammo in client.iterate("ammo", search="5.56"):
29
+ print(ammo["name"])
30
+ print(list(client.search("AK"))) # dataset names that matched
31
+ ```
32
+
33
+ Errors raise `GzwApiError` (`.status`, `.code`, `.url`). Rate-limit (honouring `Retry-After`) and 5xx responses are retried with backoff.
34
+
35
+ Game data comes from the community wiki and has its own terms: see the [data license](https://github.com/ZoniBoy00/gzw-data/blob/main/DATA_LICENSE.md). Code is MIT.
36
+
37
+ ## Development
38
+
39
+ ```bash
40
+ python -m unittest discover -s tests
41
+ ```
@@ -0,0 +1,7 @@
1
+ gzw_data/__init__.py,sha256=W4Vf9ytQtWJK21yAKgZ5xBtT2nRjuczhE7HEaI2Yp0c,198
2
+ gzw_data/client.py,sha256=xfn9VLfEgGWOjs8CLFhDKTktZzR7wzvSsSG3aCwTASk,5385
3
+ gzw_data-0.1.1.dist-info/licenses/LICENSE,sha256=ESYyLizI0WWtxMeS7rGVcX3ivMezm-HOd5WdeOh-9oU,1056
4
+ gzw_data-0.1.1.dist-info/METADATA,sha256=bSyp6VWOPv4AVUR11YUNUTB3eb07RWMwjldSSzVNP0k,1433
5
+ gzw_data-0.1.1.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
+ gzw_data-0.1.1.dist-info/top_level.txt,sha256=k5kHgwU0d_hZs8yBrWNGLKIlmitdIkXzdLdnsoKqgFE,9
7
+ gzw_data-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ gzw_data