Skip to content

Commit 4482fe7

Browse files
WilliamBergaminClaude
andauthored
perf(web): parse each sync response body once (#2069)
Co-authored-by: Claude <svc-devxp-claude@slack-corp.com>
1 parent 1101cb7 commit 4482fe7

2 files changed

Lines changed: 33 additions & 5 deletions

File tree

‎slack_sdk/web/base_client.py‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def _request_for_pagination(self, api_url: str, req_args: Dict[str, Dict[str, An
218218
return {
219219
"status_code": int(response["status"]),
220220
"headers": dict(response["headers"]),
221-
"data": json.loads(response["body"]),
221+
"data": response["parsed_body"] if "parsed_body" in response else json.loads(response["body"]),
222222
}
223223

224224
def _urllib_api_call(
@@ -306,7 +306,9 @@ def convert_params(values: dict) -> dict:
306306
response = self._perform_urllib_http_request(url=url, args=request_args) # type: ignore[arg-type]
307307
response_body = response.get("body", None)
308308
response_body_data: Optional[Union[dict, bytes]] = response_body
309-
if response_body is not None and not isinstance(response_body, bytes):
309+
if "parsed_body" in response:
310+
response_body_data = response["parsed_body"]
311+
elif response_body is not None and not isinstance(response_body, bytes):
310312
try:
311313
response_body_data = json.loads(response["body"])
312314
except json.decoder.JSONDecodeError:
@@ -413,13 +415,14 @@ def _perform_urllib_http_request(self, *, url: str, args: Dict[str, Dict[str, An
413415
body_string = resp["body"] if isinstance(resp["body"], str) else None
414416
body_bytes = body_string.encode("utf-8") if body_string is not None else resp["body"]
415417
if body_string is not None and body_string.startswith("{"):
416-
body = json.loads(body_string)
418+
parsed_body = json.loads(body_string)
419+
resp["parsed_body"] = parsed_body
417420
else:
418-
body = {} # type: ignore[assignment]
421+
parsed_body = {}
419422
retry_response = RetryHttpResponse(
420423
status_code=resp["status"],
421424
headers=resp["headers"],
422-
body=body, # type: ignore[arg-type]
425+
body=parsed_body,
423426
data=body_bytes,
424427
)
425428
for handler in self.retry_handlers:

‎tests/slack_sdk/web/test_web_client.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import re
23
import socket
34
import unittest
@@ -265,3 +266,27 @@ def test_json_requests_send_json_content_type(self):
265266
self.client.api_call("chat.postMessage", json={"channel": "C111", "text": "hi"})
266267
headers = transport.call_args[1]["args"]["headers"]
267268
self.assertEqual("application/json;charset=utf-8", headers["Content-Type"])
269+
270+
def test_api_calls_parse_the_response_body_once(self):
271+
response = {"status": 200, "headers": {}, "body": '{"ok": true}'}
272+
with patch.object(self.client, "_perform_urllib_http_request_internal", return_value=response):
273+
with patch("slack_sdk.web.base_client.json.loads", wraps=json.loads) as loads:
274+
self.client.api_test()
275+
self.assertEqual(1, loads.call_count)
276+
277+
def test_pagination_parses_each_page_body_once(self):
278+
pages = [
279+
{"status": 200, "headers": {}, "body": '{"ok": true, "response_metadata": {"next_cursor": "page-2"}}'},
280+
{"status": 200, "headers": {}, "body": '{"ok": true}'},
281+
]
282+
with patch.object(self.client, "_perform_urllib_http_request_internal", side_effect=pages):
283+
with patch("slack_sdk.web.base_client.json.loads", wraps=json.loads) as loads:
284+
self.assertEqual(2, len(list(self.client.conversations_list())))
285+
self.assertEqual(2, loads.call_count)
286+
287+
def test_non_json_response_body_raises_api_error(self):
288+
response = {"status": 200, "headers": {}, "body": "<!DOCTYPE html><html></html>"}
289+
with patch.object(self.client, "_perform_urllib_http_request_internal", return_value=response):
290+
with self.assertRaises(err.SlackApiError) as raised:
291+
self.client.api_test()
292+
self.assertTrue(raised.exception.response["error"].startswith("Received a response in a non-JSON format"))

0 commit comments

Comments
 (0)