blizzardapi2 5.0.0__tar.gz → 5.1.0__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 (70) hide show
  1. blizzardapi2-5.1.0/.agents/setup +27 -0
  2. blizzardapi2-5.1.0/.github/workflows/pr_agent.yml +24 -0
  3. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.gitignore +4 -1
  4. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/CLAUDE.md +5 -3
  5. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/PKG-INFO +3 -3
  6. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/api.py +56 -48
  7. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/battlenet/battlenet_api.py +5 -1
  8. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/blizzard_api.py +9 -1
  9. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/diablo3/diablo3_api.py +6 -1
  10. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/endpoint.py +45 -1
  11. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/hearthstone/hearthstone_api.py +1 -0
  12. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/starcraft2_api.py +6 -1
  13. blizzardapi2-5.1.0/blizzardapi2/token_manager.py +60 -0
  14. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/wow/wow_api.py +2 -0
  15. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/wow/wow_game_data_api.py +2 -1
  16. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/wow/wow_profile_api.py +41 -41
  17. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/PKG-INFO +3 -3
  18. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/SOURCES.txt +3 -0
  19. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/requires.txt +2 -2
  20. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/package-lock.json +439 -639
  21. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/package.json +3 -3
  22. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/pyproject.toml +3 -3
  23. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/conftest.py +12 -5
  24. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_base_api.py +327 -44
  25. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_battlenet.py +1 -2
  26. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_starcraft2.py +9 -7
  27. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/uv.lock +41 -41
  28. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  29. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  30. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.github/dependabot.yml +0 -0
  31. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.github/workflows/README.md +0 -0
  32. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.github/workflows/black-check.yml +0 -0
  33. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.github/workflows/python-package.yml +0 -0
  34. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.pre-commit-config.yaml +0 -0
  35. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/.release-it.cjs +0 -0
  36. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/CODE_OF_CONDUCT.md +0 -0
  37. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/CONTRIBUTING.md +0 -0
  38. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/LICENSE +0 -0
  39. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/README.md +0 -0
  40. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/SECURITY.md +0 -0
  41. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/__init__.py +0 -0
  42. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/battlenet/__init__.py +0 -0
  43. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/battlenet/battlenet_oauth_api.py +0 -0
  44. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/diablo3/__init__.py +0 -0
  45. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/diablo3/diablo3_community_api.py +0 -0
  46. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/diablo3/diablo3_game_data_api.py +0 -0
  47. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/hearthstone/__init__.py +0 -0
  48. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/hearthstone/hearthstone_game_data_api.py +0 -0
  49. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/__init__.py +0 -0
  50. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/starcraft2_community_api.py +0 -0
  51. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/starcraft2/starcraft2_game_data_api.py +0 -0
  52. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/types.py +0 -0
  53. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2/wow/__init__.py +0 -0
  54. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/dependency_links.txt +0 -0
  55. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/blizzardapi2.egg-info/top_level.txt +0 -0
  56. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/EXAMPLES.md +0 -0
  57. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/battlenet/README.md +0 -0
  58. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/diablo3/README.md +0 -0
  59. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/hearthstone/README.md +0 -0
  60. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/pull_request_template.md +0 -0
  61. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/starcraft2/README.md +0 -0
  62. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/docs/wow/README.md +0 -0
  63. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/examples/custom_session.py +0 -0
  64. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/examples/oauth_server.py +0 -0
  65. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/setup.cfg +0 -0
  66. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/__init__.py +0 -0
  67. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_diablo3.py +0 -0
  68. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_hearthstone.py +0 -0
  69. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_types.py +0 -0
  70. {blizzardapi2-5.0.0 → blizzardapi2-5.1.0}/tests/test_wow.py +0 -0
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env bash
2
+ # Prepares an Amp orb for blizzardapi2: a .venv with the package installed
3
+ # editable plus dev tools (pytest, ruff, black, isort), matching CI.
4
+ set -euo pipefail
5
+
6
+ cd "$(dirname "${BASH_SOURCE[0]}")/.."
7
+
8
+ step() {
9
+ local name="$1"
10
+ shift
11
+ local start=$SECONDS
12
+ echo "==> $name"
13
+ "$@"
14
+ echo " $name took $((SECONDS - start))s"
15
+ }
16
+
17
+ if ! command -v uv >/dev/null 2>&1; then
18
+ step "install uv" sh -c 'curl -LsSf --compressed https://astral.sh/uv/install.sh | sh'
19
+ export PATH="$HOME/.local/bin:$PATH"
20
+ fi
21
+
22
+ if [ ! -x .venv/bin/python ]; then
23
+ step "create .venv" uv venv
24
+ fi
25
+
26
+ # Same install as CI. On a warm snapshot uv only checks the installed set.
27
+ step "install dev dependencies" uv pip install -e ".[dev]"
@@ -0,0 +1,24 @@
1
+ name: PR Agent
2
+
3
+ # PR-Agent's version, model and settings live in the shared workflow in
4
+ # lostcol0ny/pr-agent-workflows; change them there, not here. This file only
5
+ # forwards events, because triggers, permissions and secrets cannot be shared.
6
+ # The shared workflow decides which of the forwarded events start a review.
7
+ on:
8
+ pull_request:
9
+ types: [opened, reopened, ready_for_review, synchronize]
10
+ issue_comment:
11
+ types: [created]
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ jobs:
17
+ pr_agent:
18
+ permissions:
19
+ contents: read
20
+ issues: write
21
+ pull-requests: write
22
+ uses: lostcol0ny/pr-agent-workflows/.github/workflows/pr_agent.yml@main
23
+ secrets:
24
+ OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
@@ -136,6 +136,7 @@ dmypy.json
136
136
 
137
137
  # Claude Code
138
138
  .claude
139
+ .claude.local.md
139
140
 
140
141
  # Test project
141
142
  test_project/
@@ -150,4 +151,6 @@ poetry.lock
150
151
  *.patch
151
152
 
152
153
  # Node deps for release-it tooling
153
- node_modules/
154
+ node_modules/
155
+ # Amp orb portals
156
+ .amp/portals/*
@@ -46,15 +46,17 @@ All API classes inherit `BaseApi` (`api.py`). New endpoint methods are thin wrap
46
46
 
47
47
  `BaseApi._make_request` has a deliberate indirection: callers pass user OAuth tokens **inside `query_params` under the key `"access_token"`**. `_make_request` `.pop()`s that key and moves the value into the `Authorization: Bearer <token>` header. This keeps tokens out of URL query strings (visible in logs/proxies). Preserve this when adding OAuth-protected endpoints — see `battlenet/battlenet_oauth_api.py:get_user_info` for the canonical shape. Don't add a separate `access_token` keyword argument to `_make_request`; the pop-from-params pattern is the contract.
48
48
 
49
- Client-credentials tokens are managed automatically: `_ensure_valid_token` lazily fetches and caches them, with a 5-minute refresh buffer (`TOKEN_REFRESH_BUFFER`). On a 401 with a client-credentials token, `_make_request` refreshes and retries once. User-supplied OAuth tokens are never refreshed by the library.
49
+ Client-credentials tokens are managed automatically: `_client_token` lazily fetches them through a thread-safe `TokenManager` (`token_manager.py`), which caches one token per OAuth host (China, and global for every other region) with a 5-minute refresh buffer (`TOKEN_REFRESH_BUFFER`). On a 401 with a client-credentials token, `_make_request` replaces that token and retries once. User-supplied OAuth tokens are never refreshed by the library.
50
+
51
+ The default session (`endpoint.default_session`) retries 429 and 5xx responses with exponential backoff via urllib3 `Retry`. A caller-supplied `session` is used unchanged.
50
52
 
51
53
  ### Region URL routing
52
54
 
53
55
  `BaseApi.OAUTH_URLS` and `API_URLS` route China (`"cn"`) to `*.battlenet.com.cn` hosts, all other regions to `oauth.battle.net` and `{region}.api.blizzard.com`. Always use `_build_oauth_url` / `_build_api_url` rather than f-stringing URLs by hand.
54
56
 
55
- ### Independent token caches per sub-API
57
+ ### Shared token cache across sub-APIs
56
58
 
57
- Each game's facade instantiates its sub-APIs with `client_id`/`client_secret`, so `WowGameDataApi`, `WowProfileApi`, `Diablo3CommunityApi`, etc. each maintain their **own** `_session` and `_access_token`. There is no shared token cache across sub-APIs. This is fine for the current API surface but worth knowing if you're debugging unexpected token-fetch behavior.
59
+ Each facade passes its `session` and `token_manager` down to every sub-API it creates, so all sub-clients of one `BlizzardApi` share one HTTP session and one token cache. Pass both when adding a sub-API. Separate top-level clients get separate caches, since they may use different credentials.
58
60
 
59
61
  ### `Region` / `Locale` enums
60
62
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: blizzardapi2
3
- Version: 5.0.0
3
+ Version: 5.1.0
4
4
  Summary: A Python wrapper for Blizzard API
5
5
  Author-email: lostcol0ny <c098os0k@4wrd.cc>
6
6
  License-Expression: MIT
@@ -18,10 +18,10 @@ Requires-Dist: pytest<10.0.0,>=8.2.2; extra == "dev"
18
18
  Requires-Dist: pytest-mock<4.0.0,>=3.14.0; extra == "dev"
19
19
  Requires-Dist: pytest-asyncio<2.0.0,>=0.23.5; extra == "dev"
20
20
  Requires-Dist: black<27.0.0,>=26.3.1; extra == "dev"
21
- Requires-Dist: isort<9.0.0,>=8.0.1; extra == "dev"
21
+ Requires-Dist: isort<10.0.0,>=8.0.1; extra == "dev"
22
22
  Requires-Dist: ruff<1.0.0,>=0.3.0; extra == "dev"
23
23
  Requires-Dist: build<2.0.0,>=1.2.0; extra == "dev"
24
- Requires-Dist: twine<7.0.0,>=5.0.0; extra == "dev"
24
+ Requires-Dist: twine<8.0.0,>=5.0.0; extra == "dev"
25
25
  Dynamic: license-file
26
26
 
27
27
  # Blizzard API 2
@@ -1,8 +1,10 @@
1
1
  """api.py file."""
2
2
 
3
- from datetime import UTC, datetime, timedelta
3
+ from datetime import timedelta
4
4
  from typing import Any, Optional
5
5
 
6
+ import requests
7
+
6
8
  from .endpoint import ApiEndpoint
7
9
  from .types import Locale, OptionalLocale, OptionalRegion, Region
8
10
 
@@ -33,21 +35,11 @@ class BaseApi(ApiEndpoint):
33
35
  DEFAULT_GET_TIMEOUT = 30.0
34
36
  DEFAULT_POST_TIMEOUT = 10.0
35
37
 
36
- def extend_endpoint(self) -> None:
37
- self._access_token: Optional[str] = None
38
- self._token_expires_at: Optional[datetime] = None
39
-
40
- def _is_token_expired(self) -> bool:
41
- """Check if the token is expiring within the refresh buffer window."""
42
- if self._token_expires_at is None:
43
- return True
44
- return datetime.now(UTC) >= self._token_expires_at - self.TOKEN_REFRESH_BUFFER
45
-
46
- def _get_client_token(self, region: str) -> dict[str, Any]:
38
+ def _get_client_token(self, region: Region | str) -> dict[str, Any]:
47
39
  """Fetch an access token using client credentials flow.
48
40
 
49
41
  Args:
50
- region: The region to query (e.g., us, eu, kr, tw, cn). Defaults to None, in which case the default region provided at instantiation is used.
42
+ region: The region whose OAuth host issues the token (e.g., us, cn).
51
43
 
52
44
  Returns:
53
45
  The token response from the API.
@@ -60,19 +52,43 @@ class BaseApi(ApiEndpoint):
60
52
  timeout=self.DEFAULT_POST_TIMEOUT,
61
53
  )
62
54
  response.raise_for_status()
63
- token_data = response.json()
55
+ return response.json()
56
+
57
+ def _client_token(
58
+ self, region: Region | str, stale_token: Optional[str] = None
59
+ ) -> str:
60
+ """Return a valid client credentials token for the region's OAuth host.
64
61
 
65
- # Store token and calculate expiration
66
- self._access_token = token_data["access_token"]
67
- expires_in = token_data.get("expires_in", 86400) # Default 24 hours
68
- self._token_expires_at = datetime.now(UTC) + timedelta(seconds=expires_in)
62
+ Tokens are cached in the shared ``token_manager``: one for China and
63
+ one for every other region.
69
64
 
70
- return token_data
65
+ Args:
66
+ region: The region to query (e.g., us, eu, kr, tw, cn).
67
+ stale_token: A token the API rejected with 401, to replace.
71
68
 
72
- def _ensure_valid_token(self, region: str) -> None:
73
- """Ensure we have a valid client credentials token."""
74
- if self._access_token is None or self._is_token_expired():
75
- self._get_client_token(region)
69
+ Returns:
70
+ The access token.
71
+ """
72
+ return self.token_manager.get_token(
73
+ self._build_oauth_url("/oauth/token", region),
74
+ lambda: self._get_client_token(region),
75
+ self.TOKEN_REFRESH_BUFFER,
76
+ stale_token=stale_token,
77
+ )
78
+
79
+ def _resolve_region(self, region: OptionalRegion) -> Region:
80
+ """Return the given region, or the default region set at instantiation.
81
+
82
+ Raises:
83
+ ValueError: If neither is set, or the region is not a valid Region.
84
+ """
85
+ resolved = region or self.region
86
+ if resolved is None:
87
+ raise ValueError(
88
+ "No Region given: pass region=... or set a default region when "
89
+ "creating the client, e.g. BlizzardApi(id, secret, region=Region.US)"
90
+ )
91
+ return Region(resolved)
76
92
 
77
93
  def _build_oauth_url(self, resource: str, region: Region | str) -> str:
78
94
  """Build URL for OAuth endpoints.
@@ -102,6 +118,15 @@ class BaseApi(ApiEndpoint):
102
118
  )
103
119
  return f"{base_url}{resource}"
104
120
 
121
+ def _get(self, url: str, params: dict[str, Any], token: str) -> requests.Response:
122
+ """Send an authenticated GET request."""
123
+ return self.session.get(
124
+ url,
125
+ params=params,
126
+ headers={"Authorization": f"Bearer {token}"},
127
+ timeout=self.DEFAULT_GET_TIMEOUT,
128
+ )
129
+
105
130
  def _make_request(
106
131
  self,
107
132
  url: str,
@@ -124,33 +149,16 @@ class BaseApi(ApiEndpoint):
124
149
  # Check if user provided their own access token
125
150
  user_token = params.pop("access_token", None)
126
151
 
127
- # Determine which token to use
128
- if user_token:
129
- # Use user-provided token (for OAuth user endpoints)
130
- token = user_token
131
- else:
132
- # Ensure client credentials token is valid
133
- self._ensure_valid_token(region)
134
- token = self._access_token
135
-
136
- # Make the request
137
- response = self.session.get(
138
- url,
139
- params=params,
140
- headers={"Authorization": f"Bearer {token}"},
141
- timeout=self.DEFAULT_GET_TIMEOUT,
142
- )
152
+ # Use the user-provided token (for OAuth user endpoints) or a client
153
+ # credentials token
154
+ token = user_token or self._client_token(region)
155
+ response = self._get(url, params, token)
143
156
 
144
157
  # Handle 401 errors for client credentials (not user tokens)
145
158
  if response.status_code == 401 and not user_token:
146
159
  # Token might have expired, refresh and retry
147
- self._get_client_token(region)
148
- response = self.session.get(
149
- url,
150
- params=params,
151
- headers={"Authorization": f"Bearer {self._access_token}"},
152
- timeout=self.DEFAULT_GET_TIMEOUT,
153
- )
160
+ token = self._client_token(region, stale_token=token)
161
+ response = self._get(url, params, token)
154
162
 
155
163
  response.raise_for_status()
156
164
  return response.json()
@@ -171,7 +179,7 @@ class BaseApi(ApiEndpoint):
171
179
  Returns:
172
180
  The API response as a dictionary.
173
181
  """
174
- _region = Region(region or self.region)
182
+ _region = self._resolve_region(region)
175
183
  url = self._build_api_url(resource, _region)
176
184
  return self._make_request(url, _region, query_params)
177
185
 
@@ -191,7 +199,7 @@ class BaseApi(ApiEndpoint):
191
199
  Returns:
192
200
  The API response as a dictionary.
193
201
  """
194
- _region = Region(region or self.region)
202
+ _region = self._resolve_region(region)
195
203
  url = self._build_oauth_url(resource, _region)
196
204
  return self._make_request(url, _region, query_params)
197
205
 
@@ -18,5 +18,9 @@ class BattlenetApi(ApiEndpoint):
18
18
  def extend_endpoint(self) -> None:
19
19
  """Init BattlenetApi."""
20
20
  self.oauth = BattlenetOAuthApi(
21
- self.client_id, self.client_secret, region=self.region, session=self.session
21
+ self.client_id,
22
+ self.client_secret,
23
+ region=self.region,
24
+ session=self.session,
25
+ token_manager=self.token_manager,
22
26
  )
@@ -35,6 +35,7 @@ class BlizzardApi(ApiEndpoint):
35
35
  region=self.region,
36
36
  locale=self.locale,
37
37
  session=self.session,
38
+ token_manager=self.token_manager,
38
39
  )
39
40
  self.diablo3 = Diablo3Api(
40
41
  self.client_id,
@@ -42,6 +43,7 @@ class BlizzardApi(ApiEndpoint):
42
43
  region=self.region,
43
44
  locale=self.locale,
44
45
  session=self.session,
46
+ token_manager=self.token_manager,
45
47
  )
46
48
  self.hearthstone = HearthstoneApi(
47
49
  self.client_id,
@@ -49,6 +51,7 @@ class BlizzardApi(ApiEndpoint):
49
51
  region=self.region,
50
52
  locale=self.locale,
51
53
  session=self.session,
54
+ token_manager=self.token_manager,
52
55
  )
53
56
  self.starcraft2 = Starcraft2Api(
54
57
  self.client_id,
@@ -56,7 +59,12 @@ class BlizzardApi(ApiEndpoint):
56
59
  region=self.region,
57
60
  locale=self.locale,
58
61
  session=self.session,
62
+ token_manager=self.token_manager,
59
63
  )
60
64
  self.battlenet = BattlenetApi(
61
- self.client_id, self.client_secret, region=self.region, session=self.session
65
+ self.client_id,
66
+ self.client_secret,
67
+ region=self.region,
68
+ session=self.session,
69
+ token_manager=self.token_manager,
62
70
  )
@@ -33,7 +33,12 @@ class Diablo3Api(ApiEndpoint):
33
33
  region=self.region,
34
34
  locale=self.locale,
35
35
  session=self.session,
36
+ token_manager=self.token_manager,
36
37
  )
37
38
  self.game_data = Diablo3GameDataApi(
38
- self.client_id, self.client_secret, region=self.region, session=self.session
39
+ self.client_id,
40
+ self.client_secret,
41
+ region=self.region,
42
+ session=self.session,
43
+ token_manager=self.token_manager,
39
44
  )
@@ -3,9 +3,37 @@
3
3
  from typing import Optional
4
4
 
5
5
  import requests
6
+ from requests.adapters import HTTPAdapter
7
+ from urllib3.util.retry import Retry
6
8
 
9
+ from .token_manager import TokenManager
7
10
  from .types import OptionalLocale, OptionalRegion
8
11
 
12
+ # Statuses retried with exponential backoff on the default session. 429 also
13
+ # honors the Retry-After header.
14
+ RETRY_STATUSES = (429, 500, 502, 503, 504)
15
+
16
+
17
+ def default_session() -> requests.Session:
18
+ """Create a session that retries rate-limited and 5xx responses.
19
+
20
+ After the last retry the final response is returned as is, so callers
21
+ still see a ``requests.HTTPError`` from ``raise_for_status``.
22
+ """
23
+ retry = Retry(
24
+ total=3,
25
+ backoff_factor=0.5,
26
+ status_forcelist=RETRY_STATUSES,
27
+ # The token POST is safe to repeat.
28
+ allowed_methods=frozenset({"GET", "POST"}),
29
+ raise_on_status=False,
30
+ )
31
+ adapter = HTTPAdapter(max_retries=retry)
32
+ session = requests.Session()
33
+ session.mount("https://", adapter)
34
+ session.mount("http://", adapter)
35
+ return session
36
+
9
37
 
10
38
  class ApiEndpoint:
11
39
  """Base endpoint.
@@ -20,6 +48,9 @@ class ApiEndpoint:
20
48
  region (Region, optional): A default region to use for requests.
21
49
  locale (Locale, optional): A default locale to use for requests.
22
50
  session (requests.Session, optional): A session object for making HTTP requests.
51
+ Defaults to a session that retries 429 and 5xx responses.
52
+ token_manager (TokenManager, optional): A client-credentials token cache to
53
+ share with other clients that use the same credentials.
23
54
  """
24
55
 
25
56
  def __init__(
@@ -30,6 +61,7 @@ class ApiEndpoint:
30
61
  region: OptionalRegion = None,
31
62
  locale: OptionalLocale = None,
32
63
  session: Optional[requests.Session] = None,
64
+ token_manager: Optional[TokenManager] = None,
33
65
  ) -> None:
34
66
  """Initialize the API endpoint.
35
67
 
@@ -42,7 +74,10 @@ class ApiEndpoint:
42
74
  self._client_secret = client_secret
43
75
  self._region = region
44
76
  self._locale = locale
45
- self._session = session if session is not None else requests.Session()
77
+ self._session = session if session is not None else default_session()
78
+ self._token_manager = (
79
+ token_manager if token_manager is not None else TokenManager()
80
+ )
46
81
  self.extend_endpoint()
47
82
 
48
83
  def extend_endpoint(self) -> None:
@@ -96,3 +131,12 @@ class ApiEndpoint:
96
131
  requests.Session: The session object for making HTTP requests
97
132
  """
98
133
  return self._session
134
+
135
+ @property
136
+ def token_manager(self) -> TokenManager:
137
+ """Get the client-credentials token cache
138
+
139
+ Returns:
140
+ TokenManager: The token cache shared with this client's sub-clients
141
+ """
142
+ return self._token_manager
@@ -40,4 +40,5 @@ class HearthstoneApi(ApiEndpoint):
40
40
  region=self.region,
41
41
  locale=self.locale,
42
42
  session=self.session,
43
+ token_manager=self.token_manager,
43
44
  )
@@ -30,7 +30,12 @@ class Starcraft2Api(ApiEndpoint):
30
30
  region=self.region,
31
31
  locale=self.locale,
32
32
  session=self.session,
33
+ token_manager=self.token_manager,
33
34
  )
34
35
  self.game_data: Starcraft2GameDataApi = Starcraft2GameDataApi(
35
- self.client_id, self.client_secret, region=self.region, session=self.session
36
+ self.client_id,
37
+ self.client_secret,
38
+ region=self.region,
39
+ session=self.session,
40
+ token_manager=self.token_manager,
36
41
  )
@@ -0,0 +1,60 @@
1
+ """Client-credentials token cache shared by the sub-clients of one facade."""
2
+
3
+ import threading
4
+ from datetime import UTC, datetime, timedelta
5
+ from typing import Any, Callable, Optional
6
+
7
+
8
+ class TokenManager:
9
+ """Thread-safe cache of client-credentials tokens, keyed by OAuth token URL.
10
+
11
+ Blizzard issues tokens per OAuth host: the global host serves us, eu, kr,
12
+ and tw, and China has its own. Keying by token URL gives one token per
13
+ host. Facades pass one manager down to every sub-client, like ``session``,
14
+ so all sub-clients of a ``BlizzardApi`` share their tokens. Share a manager
15
+ only between clients that use the same client credentials.
16
+ """
17
+
18
+ def __init__(self) -> None:
19
+ self._lock = threading.Lock() # guards _locks
20
+ self._locks: dict[str, threading.Lock] = {}
21
+ self._tokens: dict[str, tuple[str, datetime]] = {}
22
+
23
+ def get_token(
24
+ self,
25
+ token_url: str,
26
+ fetch: Callable[[], dict[str, Any]],
27
+ refresh_buffer: timedelta,
28
+ *,
29
+ stale_token: Optional[str] = None,
30
+ ) -> str:
31
+ """Return a valid token for ``token_url``, calling ``fetch`` if needed.
32
+
33
+ Args:
34
+ token_url: The OAuth token URL; tokens are cached per URL.
35
+ fetch: Fetches a new token response (``access_token``, ``expires_in``).
36
+ refresh_buffer: Refresh tokens expiring within this window.
37
+ stale_token: A token the API rejected. If it is still cached, it is
38
+ replaced; if another thread already replaced it, the newer
39
+ token is returned without fetching again.
40
+
41
+ Returns:
42
+ The access token.
43
+ """
44
+ # One lock per OAuth host, held across fetch() so concurrent callers
45
+ # wait for one refresh, while a slow host does not block the others.
46
+ with self._lock:
47
+ lock = self._locks.setdefault(token_url, threading.Lock())
48
+ with lock:
49
+ cached = self._tokens.get(token_url)
50
+ if cached is not None:
51
+ token, expires_at = cached
52
+ fresh = datetime.now(UTC) < expires_at - refresh_buffer
53
+ if fresh and token != stale_token:
54
+ return token
55
+ token_data = fetch()
56
+ token = token_data["access_token"]
57
+ expires_in = token_data.get("expires_in", 86400) # Default 24 hours
58
+ expires_at = datetime.now(UTC) + timedelta(seconds=expires_in)
59
+ self._tokens[token_url] = (token, expires_at)
60
+ return token
@@ -33,6 +33,7 @@ class WowApi(ApiEndpoint):
33
33
  region=self.region,
34
34
  locale=self.locale,
35
35
  session=self.session,
36
+ token_manager=self.token_manager,
36
37
  )
37
38
  self.profile = WowProfileApi(
38
39
  self.client_id,
@@ -40,4 +41,5 @@ class WowApi(ApiEndpoint):
40
41
  region=self.region,
41
42
  locale=self.locale,
42
43
  session=self.session,
44
+ token_manager=self.token_manager,
43
45
  )
@@ -36,7 +36,8 @@ class WowGameDataApi(LocaleApi):
36
36
  Returns:
37
37
  dict[str, Any]: the JSON response transformed to a dict structure.
38
38
  """
39
- query_params.update({"namespace": f"{namespace}-{region or self.region}"})
39
+ region = self._resolve_region(region)
40
+ query_params.update({"namespace": f"{namespace}-{region}"})
40
41
  return super().get_resource(resource, region, query_params, locale=locale)
41
42
 
42
43
  def _get_static_resource(