Skip to content

Commit 3c0413f

Browse files
authored
Improve robustness of JSON decoding (#91)
* code-style: update json CB To avoid too-many-branches in next review. * Improve robustness of JSON decoding If JSON decoding fails, if a field is missing, or if there are no fields, a ConsulException is returned. * Bump CHANGELOG.md
1 parent c115896 commit 3c0413f

File tree

3 files changed

+22
-15
lines changed

3 files changed

+22
-15
lines changed

CHANGELOG.md

+5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Change log
22

3+
## 1.5.4
4+
5+
- **feature:** Improve robustness of JSON decoding
6+
- **feature:** Add support for honoring additional arguments in consul.Consul()
7+
38
## 1.5.3
49

510
- **feature:** add replace_existing_checks option to agent.service.register()

consul/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__version__ = "1.5.3"
1+
__version__ = "1.5.4"
22

33
from consul.check import Check
44
from consul.exceptions import ACLDisabled, ACLPermissionDenied, ConsulException, NotFound, Timeout

consul/callback.py

+16-14
Original file line numberDiff line numberDiff line change
@@ -72,21 +72,23 @@ def cb(response):
7272
if response.code == 404:
7373
data = None
7474
else:
75-
data = json.loads(response.body)
76-
if decode:
77-
for item in data:
78-
if item.get(decode) is not None:
79-
item[decode] = base64.b64decode(item[decode])
80-
if is_id:
81-
data = data["ID"]
82-
if one:
83-
if data == []:
84-
data = None
85-
if data is not None:
86-
data = data[0]
87-
if postprocess:
88-
data = postprocess(data)
75+
try:
76+
data = json.loads(response.body)
77+
if decode:
78+
for item in data:
79+
if item.get(decode) is not None:
80+
item[decode] = base64.b64decode(item[decode])
81+
if is_id:
82+
data = data["ID"]
83+
if one and isinstance(data, list):
84+
data = data[0] if data else None
85+
if postprocess:
86+
data = postprocess(data)
87+
except (json.JSONDecodeError, TypeError, KeyError) as e:
88+
raise ConsulException(f"Failed to decode JSON: {response.body} {e}") from e
8989
if index:
90+
if "X-Consul-Index" not in response.headers:
91+
raise ConsulException(f"Missing index header: {response.headers}")
9092
return response.headers["X-Consul-Index"], data
9193
return data
9294

0 commit comments

Comments
 (0)