added get_response_json function to return json from aioweb
This commit is contained in:
1 parent
ae637a134f
commit
b9fbb64364
2 files changed
+120
No files matched your search
@@ -171,3 +171,43 @@ async def send_request(
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response
|
||||
|
||||
|
||||
def get_response_json(
|
||||
response: Response,
|
||||
*,
|
||||
logger: logging.Logger = LOGGER,
|
||||
expected: type | tuple[type, ...] = dict,
|
||||
**context,
|
||||
) -> dict | list | None:
|
||||
"""Parse a response body as JSON, or log it and return None.
|
||||
|
||||
aioweb's response.json() yields None for a non-JSON body, so a single
|
||||
isinstance check covers both the empty/invalid case and a body of the
|
||||
wrong shape. Callers stop on None the same way they did with the inline
|
||||
check this replaces.
|
||||
|
||||
Args:
|
||||
response: A 2xx aioweb Response from send_request.
|
||||
logger: Logger the warning is emitted on; pass the monitor's own so
|
||||
the record stays attributed to that monitor.
|
||||
expected: Type(s) the parsed body must be an instance of.
|
||||
**context: Extra fields for the warning record (category, page, ...).
|
||||
|
||||
Returns:
|
||||
The parsed body when it matches `expected`, else None.
|
||||
"""
|
||||
|
||||
data = response.json()
|
||||
if isinstance(data, expected):
|
||||
return data
|
||||
|
||||
logger.warning(
|
||||
"unexpected response",
|
||||
extra={
|
||||
**context,
|
||||
"body_type": type(data).__name__,
|
||||
"body": str(data)[:200],
|
||||
},
|
||||
)
|
||||
return None
|
||||
Reference in new issue
Block a user