Esempio n. 1
0
def _parse_response(
    *, response: httpx.Response
) -> Optional[Union[List[DatasetSnapshot], ErrorMessage, ErrorMessage,
                    HTTPValidationError]]:
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.json()
        for response_200_item_data in _response_200:
            response_200_item = DatasetSnapshot.from_dict(
                response_200_item_data)

            response_200.append(response_200_item)

        return response_200
    if response.status_code == 404:
        response_404 = ErrorMessage.from_dict(response.json())

        return response_404
    if response.status_code == 500:
        response_500 = ErrorMessage.from_dict(response.json())

        return response_500
    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422
    return None
Esempio n. 2
0
def _parse_response(*, response: httpx.Response) -> Optional[Union[str, int]]:
    if response.status_code == 200:
        response_one = response.json()
        return response_one
    if response.status_code == 201:
        response_one = response.json()
        return response_one
    return None
Esempio n. 3
0
def response_handler(r: httpx.Response) -> dict:
    try:
        r.raise_for_status()
    except httpx.HTTPStatusError as e:
        detail = r.json().get("detail", None)
        cause = "\n".join((detail, str(e))) if detail else str(e)
        raise Exception(cause).with_traceback(e.__traceback__)
    return r.json()
Esempio n. 4
0
def _parse_response(*, response: httpx.Response) -> Optional[Union[Any, HTTPValidationError]]:
    if response.status_code == 200:
        response_200 = cast(Any, response.json())
        return response_200
    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422
    return None
Esempio n. 5
0
 async def prepare_message(self, res: Response):
     message, status = await self.message_std_vals(res)
     if status == ResponseStatus.OK:
         payload = MinecraftResponse(**res.json().get("payload"))
         message += f"✅ 👤{payload.online}/{payload.max_players} 📶{payload.latency}ms"
     if status == ResponseStatus.ERROR:
         payload = ErrorPayload(**res.json().get("payload"))
         message += f"❌️ {payload.message}"
     await push_status_metric(status, self.api_endpoint)
     return message
Esempio n. 6
0
def _handle_response(response: httpx.Response) -> RevenueCatResponse:
    if response.status_code not in [200, 201]:
        raise RevenueCatError(message=response.json().get("message"),
                              http_status=response.status_code,
                              json_body=response.json(),
                              headers=response.headers)

    return RevenueCatResponse(http_status=response.status_code,
                              json_body=response.json(),
                              headers=response.headers)
Esempio n. 7
0
 async def prepare_message(self, res: Response):
     message, status = await self.message_std_vals(res)
     if status == ResponseStatus.OK:
         payload = ICMPCheckerResponse(**res.json().get("payload"))
         message += f"✅ {payload.min_rtt}/{payload.max_rtt}/{payload.avg_rtt} " \
                    f"⬆{payload.packets_sent} ️⬇️{payload.packets_received} Loss: {payload.loss}"
     if status == ResponseStatus.ERROR:
         payload = ErrorPayload(**res.json().get("payload"))
         message += f"❌️ {payload.message}"
     await push_status_metric(status, self.api_endpoint)
     return message
Esempio n. 8
0
 async def prepare_message(self, res: Response):
     message, status = await self.message_std_vals(res)
     if status == ResponseStatus.OK:
         payload = HttpCheckerResponse(**res.json().get("payload"))
         message += f"{HTTP_EMOJI.get(payload.status_code // 100, '')} " \
                    f"{payload.status_code}, ⏰ {payload.time * 1000:.2f}ms"
     if status == ResponseStatus.ERROR:
         payload = ErrorPayload(**res.json().get("payload"))
         message += f"❌️ {payload.message}"
     await push_status_metric(status, self.api_endpoint)
     return message
def _parse_response(
    *, response: httpx.Response
) -> Optional[Union[PostBodyMultipartResponse200, PublicError]]:
    if response.status_code == 200:
        response_200 = PostBodyMultipartResponse200.from_dict(response.json())

        return response_200
    if response.status_code == 400:
        response_400 = PublicError.from_dict(response.json())

        return response_400
    return None
Esempio n. 10
0
 async def prepare_message(self, res: Response):
     message, status = await self.message_std_vals(res)
     if status == ResponseStatus.OK:
         payload = PortResponse(**res.json().get("payload"))
         if payload.open:
             message += "✅ Порт ОТКРЫТ"
         else:
             message += "❌️ Порт ЗАКРЫТ"
     if status == ResponseStatus.ERROR:
         payload = ErrorPayload(**res.json().get("payload"))
         message += f"❌️ {payload.message}"
     await push_status_metric(status, self.api_endpoint)
     return message
Esempio n. 11
0
def _post_process_response(method: str, spec: dict,
                           response: httpx.Response) -> Any:
    """
    Пост-обработка ответа API с конвертацией данных в типы Python отсутствующие в JSON
    """
    schema = spec.get('responses', EMPTY).get(str(response.status_code))
    if schema and 'content' in schema:
        content_type = response.headers.get('content-type')
        schema = schema.get('content', EMPTY).get(content_type,
                                                  EMPTY).get('schema')
        if schema:
            return _post_process_json(response.json(), schema)
    return response.json()
Esempio n. 12
0
def _parse_response(*, response: httpx.Response) -> Optional[Union[List[AModel], HTTPValidationError]]:
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.json()
        for response_200_item_data in _response_200:
            response_200_item = AModel.from_dict(response_200_item_data)

            response_200.append(response_200_item)

        return response_200
    if response.status_code == 422:
        response_422 = HTTPValidationError.from_dict(response.json())

        return response_422
    return None
def _parse_response(
        *, response: httpx.Response) -> Optional[ReleaseImportAllResponse]:
    if response.status_code == 200:
        response_200 = ReleaseImportAllResponse.from_dict(response.json())

        return response_200
    return None
Esempio n. 14
0
def _parse_response(
        *, response: httpx.Response) -> Optional[DatasetInfoResponse200]:
    if response.status_code == 200:
        response_200 = DatasetInfoResponse200.from_dict(response.json())

        return response_200
    return None
Esempio n. 15
0
def _parse_response(
        *, response: httpx.Response) -> Optional[Union[ApiResponse, None]]:
    if response.status_code == 200:
        response_200 = ApiResponse.from_dict(response.json())

        return response_200
    if response.status_code == 400:
        response_400 = None

        return response_400
    if response.status_code == 401:
        response_401 = None

        return response_401
    if response.status_code == 403:
        response_403 = None

        return response_403
    if response.status_code == 404:
        response_404 = None

        return response_404
    if response.status_code == 409:
        response_409 = None

        return response_409
    if response.status_code == 500:
        response_500 = None

        return response_500
    return None
Esempio n. 16
0
def _parse_response(
        *, response: httpx.Response) -> Optional[ConnectionModuleResponse]:
    if response.status_code == 200:
        response_200 = ConnectionModuleResponse.from_dict(response.json())

        return response_200
    return None
Esempio n. 17
0
def _parse_response(
        *, response: httpx.Response) -> Optional[Union[List[Admin], None]]:
    if response.status_code == 200:
        response_200 = []
        _response_200 = response.json()
        for response_200_item_data in _response_200:
            response_200_item = Admin.from_dict(response_200_item_data)

            response_200.append(response_200_item)

        return response_200
    if response.status_code == 400:
        response_400 = None

        return response_400
    if response.status_code == 401:
        response_401 = None

        return response_401
    if response.status_code == 403:
        response_403 = None

        return response_403
    if response.status_code == 500:
        response_500 = None

        return response_500
    return None
Esempio n. 18
0
def unenvelope_or_raise_error(resp: httpx.Response) -> Dict:
    """
    Director responses are enveloped
    If successful response, we un-envelop it and return data as a dict
    If error, it raise an HTTPException
    """
    body = resp.json()

    assert "data" in body or "error" in body  # nosec
    data = body.get("data")
    error = body.get("error")

    if codes.is_server_error(resp.status_code):
        logger.error(
            "director error %d [%s]: %s",
            resp.status_code,
            resp.reason_phrase,
            error,
        )
        raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE)

    if codes.is_client_error(resp.status_code):
        msg = error or resp.reason_phrase
        raise HTTPException(resp.status_code, detail=msg)

    return data or {}
Esempio n. 19
0
def _parse_response(
    *, response: httpx.Response
) -> Optional[Union[User, ErrorMessage, ErrorMessage]]:
    if response.status_code == 200:
        response_200 = User.from_dict(response.json())

        return response_200
    if response.status_code == 404:
        response_404 = ErrorMessage.from_dict(response.json())

        return response_404
    if response.status_code == 500:
        response_500 = ErrorMessage.from_dict(response.json())

        return response_500
    return None
Esempio n. 20
0
def _parse_response(*,
                    response: httpx.Response) -> Optional[ResolverConnection]:
    if response.status_code == 200:
        response_200 = ResolverConnection.from_dict(response.json())

        return response_200
    return None
Esempio n. 21
0
    async def to_data_queue(self, offset: int, response: Response) -> bool:
        """
        Flushes buffer, transforms data to Record to be sent to the data queue
        then returns a boolean based on if all data has been retrieved by the API.

        :param response: Response Object from API query
        :return: bool
        """
        from service_logic import app

        json_payload: dict = response.json()
        self.add_item({'offset': offset, 'payload': json_payload})
        if self.is_full:
            record = Record(buffer_list=self.flush())
            await app.data_queue.put(record)

        if len(json_payload) < app.api_pagination_limit:
            while True:
                # Ensure buffer is completely flushed
                if app.buffer.is_empty:
                    break
                else:
                    record = Record(buffer_list=self.flush())
                    await app.data_queue.put(record)
            return True
        else:
            return False
Esempio n. 22
0
    def _report_device(item, _res: Response):
        if _res.is_error:
            print(f"FAIL: create device {item['hostname']}: {_res.text}")
            return

        print(f"CREATE:OK: device {item['hostname']} ... creating primary IP ... ")
        nb_col.source_records.append(_res.json())
Esempio n. 23
0
    def _handle_task_creation_response(
            cls, response: httpx.Response) -> List["Task"]:
        result = response.json()
        if "warnings" in result:
            warnings = result["warnings"]
            if len(warnings) > 0:
                logger.warning(
                    f"There were {len(warnings)} warnings during task creation:"
                )
            for warning in warnings:
                logger.warning(warning)
        assert "tasks" in result, "Invalid result of task creation"

        successes = []
        errors = []
        for t in result["tasks"]:
            print(t)
            if "success" in t:
                successes.append(t["success"])
            if "error" in t:
                errors.append(t["error"])
        if len(errors) > 0:
            logger.error(f"{len(errors)} tasks could not be created:")
            for error in errors:
                logger.error(error)
        if len(successes) > 0:
            logger.info(f"{len(successes)} tasks were successfully created.")
        return [cls._from_dict(t) for t in successes]
Esempio n. 24
0
    def _parse_home_response(self, response: httpx.Response) -> None:
        data = response.json()

        LOGGER.debug(f"Home response: {data}")

        if data["home_screen"][0]["status"] == "Offline":
            LOGGER.warning(f"Status for system {self.serial} is Offline.")
            raise AqualinkSystemOfflineException

        self.temp_unit = data["home_screen"][3]["temp_scale"]

        # Make the data a bit flatter.
        devices = {}
        for x in data["home_screen"][4:]:
            name = list(x.keys())[0]
            state = list(x.values())[0]
            attrs = {"name": name, "state": state}
            devices.update({name: attrs})

        for k, v in devices.items():
            if k in self.devices:
                for dk, dv in v.items():
                    self.devices[k].data[dk] = dv
            else:
                self.devices[k] = IaquaDevice.from_data(self, v)
Esempio n. 25
0
 def __init__(self,
              request: httpx.Request = None,
              response: httpx.Response = None) -> None:
     self.status = meta_v1.Status.from_dict(response.json())
     super().__init__(self.status.message,
                      request=request,
                      response=response)
Esempio n. 26
0
def _json_or_panic(response: Response) -> dict:
    try:
        return response.json()
    except JSONDecodeError:
        raise NetSchoolAPIError(
            f"{response.status_code}: {response.url.path}: {response.content}",
        ) from None
Esempio n. 27
0
    def _parse_error(res: httpx.Response) -> ApiError:
        """
        Errors should contain a "status" field with a human readable explanation of
        what went wrong as well as a "error_type" field indicating the kind of error that can be mapped
        to a Python type.

        There's a fallback error UnknownApiError for other types of exceptions (network issues, api
        gateway problems, etc.)
        """
        try:
            body = res.json()
        except JSONDecodeError:
            raise UnknownApiError(res.text)

        if "error_type" not in body:
            raise UnknownApiError(str(body))

        error_type = body["error_type"]
        status = body["status"]

        if re.search(r"[0-9]+ qubits were requested, but the QVM is limited to [0-9]+ qubits.", status):
            return TooManyQubitsError(status)

        error_cls = error_mapping.get(error_type, UnknownApiError)
        return error_cls(status)
def _parse_response(
        *, response: httpx.Response) -> Optional[ProjectInfoByNameResponse200]:
    if response.status_code == 200:
        response_200 = ProjectInfoByNameResponse200.from_dict(response.json())

        return response_200
    return None
def _parse_response(
        *, response: httpx.Response) -> Optional[PaginatedPipelineList]:
    if response.status_code == 200:
        response_200 = PaginatedPipelineList.from_dict(response.json())

        return response_200
    return None
Esempio n. 30
0
def _parse_response(
        *, response: httpx.Response) -> Optional[TestInlineObjectsResponse200]:
    if response.status_code == 200:
        response_200 = TestInlineObjectsResponse200.from_dict(response.json())

        return response_200
    return None