gzw-data 0.1.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.
gzw_data-0.1.1/LICENSE ADDED
@@ -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,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,28 @@
1
+ # gzw-data (Python)
2
+
3
+ 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.
4
+
5
+ ```bash
6
+ pip install git+https://github.com/ZoniBoy00/gzw-data-py
7
+ ```
8
+
9
+ ```python
10
+ from gzw_data import GzwDataClient
11
+
12
+ client = GzwDataClient() # no API key needed
13
+ print(client.datasets()) # {'ammo': 79, 'weapons': 44, ...}
14
+ print(client.get("weapons", "ak-12")["name"]) # AK-12
15
+ for ammo in client.iterate("ammo", search="5.56"):
16
+ print(ammo["name"])
17
+ print(list(client.search("AK"))) # dataset names that matched
18
+ ```
19
+
20
+ Errors raise `GzwApiError` (`.status`, `.code`, `.url`). Rate-limit (honouring `Retry-After`) and 5xx responses are retried with backoff.
21
+
22
+ 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.
23
+
24
+ ## Development
25
+
26
+ ```bash
27
+ python -m unittest discover -s tests
28
+ ```
@@ -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"
@@ -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,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ gzw_data/__init__.py
5
+ gzw_data/client.py
6
+ gzw_data.egg-info/PKG-INFO
7
+ gzw_data.egg-info/SOURCES.txt
8
+ gzw_data.egg-info/dependency_links.txt
9
+ gzw_data.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ gzw_data
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gzw-data"
7
+ version = "0.1.1"
8
+ description = "Python client for the free Gray Zone Warfare data API (gzw-data.dev)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ keywords = ["gray-zone-warfare", "gzw", "api", "game-data"]
13
+ dependencies = []
14
+
15
+ [project.urls]
16
+ Homepage = "https://gzw-data.dev/"
17
+ Source = "https://github.com/ZoniBoy00/gzw-data-py"
18
+
19
+ [tool.setuptools]
20
+ packages = ["gzw_data"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,117 @@
1
+ import io
2
+ import json
3
+ import unittest
4
+ import urllib.error
5
+
6
+ from gzw_data import GzwApiError, GzwDataClient
7
+
8
+
9
+ class FakeResponse(io.BytesIO):
10
+ def __enter__(self):
11
+ return self
12
+
13
+ def __exit__(self, *exc):
14
+ return False
15
+
16
+
17
+ def envelope(data, **extra):
18
+ return FakeResponse(json.dumps({"data": data, **extra}).encode())
19
+
20
+
21
+ def http_error(req, status, code, message="err", headers=None):
22
+ body = json.dumps({"error": {"code": code, "message": message}}).encode()
23
+ return urllib.error.HTTPError(req.full_url, status, message, headers or {}, io.BytesIO(body))
24
+
25
+
26
+ class ClientTests(unittest.TestCase):
27
+ def test_list_builds_query_and_skips_none(self):
28
+ seen = []
29
+
30
+ def opener(req, timeout):
31
+ seen.append(req.full_url)
32
+ return envelope([{"id": "a"}], totalPages=1)
33
+
34
+ GzwDataClient(opener=opener).list("weapons", page=2, per_page=5, caliber="5.56")
35
+ self.assertEqual(len(seen), 1)
36
+ self.assertIn("/weapons?", seen[0])
37
+ self.assertIn("page=2", seen[0])
38
+ self.assertIn("caliber=5.56", seen[0])
39
+ self.assertNotIn("search", seen[0])
40
+
41
+ def test_iterate_follows_pages(self):
42
+ pages = {"1": [{"id": 1}, {"id": 2}], "2": [{"id": 3}]}
43
+
44
+ def opener(req, timeout):
45
+ page = req.full_url.split("page=")[1].split("&")[0]
46
+ return envelope(pages[page], totalPages=2)
47
+
48
+ ids = [r["id"] for r in GzwDataClient(opener=opener).iterate("ammo")]
49
+ self.assertEqual(ids, [1, 2, 3])
50
+
51
+ def test_get_returns_none_when_missing(self):
52
+ def opener(req, timeout):
53
+ raise http_error(req, 404, "RECORD_NOT_FOUND")
54
+
55
+ self.assertIsNone(GzwDataClient(opener=opener).get("weapons", "x"))
56
+
57
+ def test_retries_then_raises_structured_error(self):
58
+ calls = []
59
+
60
+ def opener(req, timeout):
61
+ calls.append(1)
62
+ raise http_error(req, 429, "RATE_LIMITED")
63
+
64
+ client = GzwDataClient(opener=opener, retries=1)
65
+ with self.assertRaises(GzwApiError) as ctx:
66
+ client.request("stats")
67
+ self.assertEqual(len(calls), 2)
68
+ self.assertEqual(ctx.exception.code, "RATE_LIMITED")
69
+ self.assertEqual(ctx.exception.status, 429)
70
+
71
+ def test_honours_retry_after_header(self):
72
+ from unittest import mock
73
+
74
+ calls = []
75
+
76
+ def opener(req, timeout):
77
+ calls.append(1)
78
+ if len(calls) == 1:
79
+ raise http_error(req, 429, "RATE_LIMITED", headers={"Retry-After": "7"})
80
+ return envelope({"ok": True})
81
+
82
+ with mock.patch("gzw_data.client.time.sleep") as sleep:
83
+ result = GzwDataClient(opener=opener).request("health")
84
+ sleep.assert_called_once_with(7.0)
85
+ self.assertEqual(result["data"], {"ok": True})
86
+
87
+ def test_retry_after_is_capped(self):
88
+ from unittest import mock
89
+
90
+ def opener(req, timeout):
91
+ raise http_error(req, 429, "RATE_LIMITED", headers={"Retry-After": "600"})
92
+
93
+ with mock.patch("gzw_data.client.time.sleep") as sleep, self.assertRaises(GzwApiError) as ctx:
94
+ GzwDataClient(opener=opener, retries=1, max_retry_wait=30).request("health")
95
+ sleep.assert_called_once_with(30)
96
+ self.assertEqual(ctx.exception.retry_after, 600.0)
97
+
98
+ def test_does_not_retry_client_errors(self):
99
+ calls = []
100
+
101
+ def opener(req, timeout):
102
+ calls.append(1)
103
+ raise http_error(req, 400, "BAD_REQUEST")
104
+
105
+ with self.assertRaises(GzwApiError):
106
+ GzwDataClient(opener=opener).request("weapons")
107
+ self.assertEqual(len(calls), 1)
108
+
109
+ def test_datasets_maps_counts(self):
110
+ def opener(req, timeout):
111
+ return envelope({"ammo": {"total": 79}, "weapons": {"total": 44}})
112
+
113
+ self.assertEqual(GzwDataClient(opener=opener).datasets(), {"ammo": 79, "weapons": 44})
114
+
115
+
116
+ if __name__ == "__main__":
117
+ unittest.main()