Skip to content

Commit

Permalink
Merge pull request #14 from chkp-orso/master
Browse files Browse the repository at this point in the history
Fix json.loads to handle bytes in python 3.0-3.5
  • Loading branch information
chkp-yaelg committed Mar 17, 2019
2 parents 2272305 + 85fcc93 commit 84d2a5f
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 9 deletions.
4 changes: 3 additions & 1 deletion cpapi/api_response.py
@@ -1,6 +1,8 @@
import json
import sys

from cpapi.utils import compatible_loads

# compatible import for python 2 and 3
from .api_exceptions import APIException
if sys.version_info >= (3, 0):
Expand Down Expand Up @@ -55,7 +57,7 @@ def __init__(self, json_response, success, status_code=None, err_message=""):
if isinstance(json_response, dict):
data_dict = json_response
else:
data_dict = json.loads(json_response)
data_dict = compatible_loads(json_response)
except ValueError:
raise APIException("APIResponse received a response which is not a valid JSON.", json_response)
else:
Expand Down
7 changes: 4 additions & 3 deletions cpapi/cli.py
Expand Up @@ -8,6 +8,7 @@
import sys
import traceback

from cpapi.utils import compatible_loads
from . import APIClient, APIClientArgs

if sys.version_info < (3,):
Expand Down Expand Up @@ -85,7 +86,7 @@ def to_obj(self):
if len(self) == 1 and self[0][0] is Pairs.NO_KEY:
val = self[0][1]
if val in {'null', 'true', 'false'} or val[0] in '"{[':
return json.loads(val)
return compatible_loads(val)
elif re.match(r'\d+$', val):
return int(val, 10)
return val
Expand Down Expand Up @@ -292,8 +293,8 @@ def main(argv):
client_args[cla] = val
debug('client args: %s\n' % client_args)
args.domain = getattr(args, 'domain', None)
args.root = json.loads(getattr(args, 'root', 'false'))
args.sync = json.loads(getattr(args, 'sync', 'true'))
args.root = compatible_loads(getattr(args, 'root', 'false'))
args.sync = compatible_loads(getattr(args, 'sync', 'true'))
with APIClient(APIClientArgs(**client_args)) as client:
call_args = {}
if hasattr(args, 'session_id'):
Expand Down
12 changes: 7 additions & 5 deletions cpapi/mgmt_api.py
Expand Up @@ -27,6 +27,8 @@
import subprocess
import time

from cpapi.utils import compatible_loads


class APIClientArgs:
"""
Expand Down Expand Up @@ -192,8 +194,8 @@ def login_as_root(self, domain=None, payload=None):
port = self.get_port()
else:
try:
port = json.loads(subprocess.check_output([python_absolute_path,
api_get_port_absolute_path, "-f", "json"]))["external_port"]
port = compatible_loads(subprocess.check_output([python_absolute_path,
api_get_port_absolute_path, "-f", "json"]))["external_port"]
# if can't, default back to what the user wrote or the default (443)
except (ValueError, subprocess.CalledProcessError):
port = self.get_port()
Expand All @@ -207,7 +209,7 @@ def login_as_root(self, domain=None, payload=None):
new_payload += [key, payload[key]]
if domain:
new_payload += ["domain", domain]
login_response = json.loads(subprocess.check_output(
login_response = compatible_loads(subprocess.check_output(
[mgmt_cli_absolute_path, "login", "-r", "true", "-f", "json", "--port", str(port)] + new_payload))
self.sid = login_response["sid"]
self.server = "127.0.0.1"
Expand Down Expand Up @@ -305,15 +307,15 @@ def api_call(self, command, payload=None, sid=None, wait_for_task=True):
# When the command is 'login' we'd like to convert the password to "****" so that it
# would not appear as plaintext in the debug file.
if command == "login":
json_data = json.loads(_data)
json_data = compatible_loads(_data)
json_data["password"] = "****"
_data = json.dumps(json_data)

# Store the request and the reply (for debug purpose).
_api_log = {
"request": {
"url": url,
"payload": json.loads(_data),
"payload": compatible_loads(_data),
"headers": _headers
},
"response": res.response()
Expand Down
13 changes: 13 additions & 0 deletions cpapi/utils.py
@@ -0,0 +1,13 @@
import json
import sys


def compatible_loads(json_data):
"""
Function json.loads in python 3.0 - 3.5 can't handle bytes, so this function handle it.
:param json_data:
:return: unicode (str if it's python 3)
"""
if isinstance(json_data, bytes) and (3, 0) <= sys.version_info < (3, 6):
json_data = json_data.decode("utf-8")
return json.loads(json_data)

0 comments on commit 84d2a5f

Please sign in to comment.