Passed
Pull Request — main (#48)
by Guy
01:40
created

ims_envista.commons.on_request_chunk_sent_debug()   A

Complexity

Conditions 3

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
"""IMS Envista Commons."""
2
3
import http
4
import logging
5
from json import JSONDecodeError
6
from typing import Any
7
from uuid import UUID
8
9
from aiohttp import (
10
    ClientError,
11
    ClientSession,
12
    TraceRequestChunkSentParams,
13
    TraceRequestEndParams,
14
    TraceRequestStartParams,
15
)
16
17
logger = logging.getLogger(__name__)
18
19
class IMSEnvistaError(Exception):
20
    """
21
    Exception raised for errors in the IMS Envista API.
22
23
    Attributes
24
    ----------
25
        error -- description of the error
26
27
    """
28
29
    def __init__(self, error: str) -> None:
30
        self.error = error
31
        super().__init__(f"{self.error}")
32
33
async def on_request_start_debug(session: ClientSession, context,params: TraceRequestStartParams) -> None:  # noqa: ANN001, ARG001
34
    logger.debug("HTTP %s: %s", params.method, params.url)
35
36
37
async def on_request_chunk_sent_debug(
38
    session: ClientSession, context, params: TraceRequestChunkSentParams  # noqa: ANN001, ARG001
39
) -> None:
40
    if (params.method in ("POST", "PUT")) and params.chunk:
41
        logger.debug("HTTP Content %s: %s", params.method, params.chunk)
42
43
44
async def on_request_end_debug(session: ClientSession, context, params: TraceRequestEndParams) -> None:  # noqa: ANN001, ARG001
45
    response_text = await params.response.text()
46
    logger.debug("HTTP %s Response <%s>: %s", params.method, params.response.status, response_text)
47
48
49
def get_headers(token: UUID | str) -> dict[str, str]:
50
    return {
51
        "Accept": "application/vnd.github.v3.text-match+json",
52
        "Authorization": f"ApiToken {token!s}"
53
    }
54
55
async def get(
56
    session: ClientSession, url: str, token: UUID | str, headers: dict | None = None
57
) -> dict[str, Any]:
58
    try:
59
        if not headers:
60
            headers = get_headers(token)
61
62
        resp = await session.get(url=url, headers=headers)
63
        json_resp: dict = await resp.json(content_type=None)
64
    except TimeoutError as ex:
65
        msg = f"Failed to communicate with IMS Envista API due to time out: ({ex!s})"
66
        raise IMSEnvistaError(msg) from ex
67
    except ClientError as ex:
68
        msg = f"Failed to communicate with  IMS Envistadue to ClientError: ({ex!s})"
69
        raise IMSEnvistaError(msg) from ex
70
    except JSONDecodeError as ex:
71
        msg = f"Received invalid response from IMS Envista API: {ex!s}"
72
        raise IMSEnvistaError(msg) from ex
73
74
    if resp.status != http.HTTPStatus.OK:
75
        msg = f"Received Error from IMS Envista API: {resp.status, resp.reason}"
76
        raise IMSEnvistaError(msg)
77
78
    return json_resp
79