Skip to content

Commit

Permalink
Compatibility issues with JSONDecodeError
Browse files Browse the repository at this point in the history
`requests` is somewhat inconsistent with how it raises this exception.
(psf/requests#5794)

Depending on the environment, the following can happen during
`response.json`:

  - Python2 and no `simplejson`, a `ValueError` will be raised
  - Python2 and `simplejson`, a `simplejson.JSONDecodeError` will be
    raised
  - Python3 and no `simplejson`, a `json.JSONDecodeError` will be raised
  - Python3 and `simplejson`, a `simplejson.JSONDecodeError` will be
    raised

The following wil make sure that catching
`transifex.api.jsonapi.compat.JSONDecodeError` in a `try:
response.json()`
block will always work
  • Loading branch information
Konstantinos Bairaktaris committed Sep 9, 2021
1 parent ec29fd1 commit e425373
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
1 change: 0 additions & 1 deletion transifex/api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1011,7 +1011,6 @@ child = family_api.Child.create(attributes={'name': "Hercules"},
relationships={'parent': {'data': {'type': "parents": 'id': "1"}}})
```


This way, you can reuse a relationship from another object when creating,
without having to fetch the relationship:

Expand Down
27 changes: 25 additions & 2 deletions transifex/api/jsonapi/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,33 @@

import json

# `requests` is somewhat inconsistent with how it raises this exception.
# (https://github.com/psf/requests/issues/5794)
#
# Depending on the environment, the following can happen during
# `response.json`:
#
# - Python2 and no `simplejson`, a `ValueError` will be raised
# - Python2 and `simplejson`, a `simplejson.JSONDecodeError` will be raised
# - Python3 and no `simplejson`, a `json.JSONDecodeError` will be raised
# - Python3 and `simplejson`, a `simplejson.JSONDecodeError` will be raised
#
# The following wil make sure that catching
# `transifex.api.jsonapi.compat.JSONDecodeError` in a `try: response.json()`
# block will always work
JSONDecodeError = []
try:
JSONDecodeError = json.JSONDecodeError
JSONDecodeError.append(json.JSONDecodeError)
except AttributeError:
JSONDecodeError = ValueError
pass
try:
import simplejson
JSONDecodeError.append(simplejson.JSONDecodeError)
except ImportError:
pass
if not JSONDecodeError:
JSONDecodeError = [ValueError]
JSONDecodeError = tuple(JSONDecodeError)

try:
import collections.abc as abc
Expand Down

0 comments on commit e425373

Please sign in to comment.