Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix can_parse_as_json #5177

Merged
merged 1 commit into from Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 4 additions & 5 deletions mlflow/utils/rest_utils.py
Expand Up @@ -147,10 +147,9 @@ def http_request(
raise MlflowException("API request to %s failed with exception %s" % (url, e))


def _can_parse_as_json(string):
def _can_parse_as_json_object(string):
try:
json.loads(string)
return True
return isinstance(json.loads(string), dict)
except Exception:
return False

Expand All @@ -166,7 +165,7 @@ def http_request_safe(host_creds, endpoint, method, **kwargs):
def verify_rest_response(response, endpoint):
"""Verify the return code and format, raise exception if the request was not successful."""
if response.status_code != 200:
if _can_parse_as_json(response.text):
if _can_parse_as_json_object(response.text):
raise RestException(json.loads(response.text))
else:
base_msg = "API request to endpoint %s failed with error code " "%s != 200" % (
Expand All @@ -177,7 +176,7 @@ def verify_rest_response(response, endpoint):

# Skip validation for endpoints (e.g. DBFS file-download API) which may return a non-JSON
# response
if endpoint.startswith(_REST_API_PATH_PREFIX) and not _can_parse_as_json(response.text):
if endpoint.startswith(_REST_API_PATH_PREFIX) and not _can_parse_as_json_object(response.text):
base_msg = (
"API request to endpoint was successful but the response body was not "
"in a valid JSON format"
Expand Down
10 changes: 10 additions & 0 deletions tests/utils/test_rest_utils.py
Expand Up @@ -13,6 +13,7 @@
_DEFAULT_HEADERS,
call_endpoint,
call_endpoints,
_can_parse_as_json_object,
)
from mlflow.protos.service_pb2 import GetRun
from mlflow.protos.databricks_pb2 import ENDPOINT_NOT_FOUND, ErrorCode
Expand Down Expand Up @@ -312,3 +313,12 @@ def test_numpy_encoder_fail():
with pytest.raises(TypeError, match="not JSON serializable"):
ne = NumpyEncoder()
ne.default(test_number)


def test_can_parse_as_json_object():
assert _can_parse_as_json_object("{}")
assert _can_parse_as_json_object('{"a": "b"}')
assert _can_parse_as_json_object('{"a": {"b": "c"}}')
assert not _can_parse_as_json_object("[0, 1, 2]")
assert not _can_parse_as_json_object('"abc"')
assert not _can_parse_as_json_object("123")