From a6448f47a275d63b8239653b99d0da928b1eba0d Mon Sep 17 00:00:00 2001 From: Bob Weinand Date: Fri, 7 Jun 2024 14:34:12 +0200 Subject: [PATCH] Fix response data forwarding --- ddapm_test_agent/agent.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ddapm_test_agent/agent.py b/ddapm_test_agent/agent.py index 74aa6e0..7fa0d8b 100644 --- a/ddapm_test_agent/agent.py +++ b/ddapm_test_agent/agent.py @@ -125,7 +125,8 @@ async def handle_exception_middleware(request: Request, handler: _Handler) -> we return web.HTTPBadRequest(reason=str(e)) -async def _forward_request(request_data: bytes, headers: Mapping[str, str], full_agent_url: str) -> ClientResponse: +async def _forward_request(request_data: bytes, headers: Mapping[str, str], full_agent_url: str) -> tuple[ + ClientResponse, str]: async with ClientSession() as session: async with session.post( full_agent_url, @@ -134,7 +135,10 @@ async def _forward_request(request_data: bytes, headers: Mapping[str, str], full ) as resp: assert resp.status == 200, f"Request to agent unsuccessful, received [{resp.status}] response." - if "text/html" in resp.content_type: + if "text/plain" in resp.content_type: + raw_response_data = await resp.text() + log.info("Response %r from agent:", raw_response_data) + else: raw_response_data = await resp.read() if len(raw_response_data) == 0: log.info("Received empty response: %r from agent.", raw_response_data) @@ -148,11 +152,7 @@ async def _forward_request(request_data: bytes, headers: Mapping[str, str], full log.warning("Original Request: %r", request_data) response_data = "" log.info("Response %r from agent:", response_data) - elif "text/plain" in resp.content_type: - log.info("Response %r from agent:", await resp.text()) - else: - log.info("Response %r from agent:", await resp.json()) - return resp + return resp, raw_response_data async def _prepare_and_send_request(data: bytes, request: Request, headers: Mapping[str, str]) -> web.Response: @@ -165,11 +165,11 @@ async def _prepare_and_send_request(data: bytes, request: Request, headers: Mapp log.info("Forwarding request to agent at %r", full_agent_url) log.debug(f"Using headers: {headers}") - client_response = await _forward_request(data, headers, full_agent_url) + (client_response, body) = await _forward_request(data, headers, full_agent_url) return web.Response( status=client_response.status, headers=client_response.headers, - body=await client_response.read(), + body=body, )