Skip to content

Commit

Permalink
Improve robustness of JSON decoding (#91)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
cpaillet authored Jan 9, 2025
1 parent c115896 commit 3c0413f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 15 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Change log

## 1.5.4

- **feature:** Improve robustness of JSON decoding
- **feature:** Add support for honoring additional arguments in consul.Consul()

## 1.5.3

- **feature:** add replace_existing_checks option to agent.service.register()
Expand Down
2 changes: 1 addition & 1 deletion consul/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "1.5.3"
__version__ = "1.5.4"

from consul.check import Check
from consul.exceptions import ACLDisabled, ACLPermissionDenied, ConsulException, NotFound, Timeout
Expand Down
30 changes: 16 additions & 14 deletions consul/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,21 +72,23 @@ def cb(response):
if response.code == 404:
data = None
else:
data = json.loads(response.body)
if decode:
for item in data:
if item.get(decode) is not None:
item[decode] = base64.b64decode(item[decode])
if is_id:
data = data["ID"]
if one:
if data == []:
data = None
if data is not None:
data = data[0]
if postprocess:
data = postprocess(data)
try:
data = json.loads(response.body)
if decode:
for item in data:
if item.get(decode) is not None:
item[decode] = base64.b64decode(item[decode])
if is_id:
data = data["ID"]
if one and isinstance(data, list):
data = data[0] if data else None
if postprocess:
data = postprocess(data)
except (json.JSONDecodeError, TypeError, KeyError) as e:
raise ConsulException(f"Failed to decode JSON: {response.body} {e}") from e
if index:
if "X-Consul-Index" not in response.headers:
raise ConsulException(f"Missing index header: {response.headers}")
return response.headers["X-Consul-Index"], data
return data

Expand Down

0 comments on commit 3c0413f

Please sign in to comment.