Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /MTSWebServices_horizon /horizon /client /base.py
| # SPDX-FileCopyrightText: 2023-present MTS PJSC | |
| # SPDX-License-Identifier: Apache-2.0 | |
| from __future__ import annotations | |
| import http | |
| import logging | |
| import pprint | |
| import warnings | |
| from typing import Any, Generic, TypeVar | |
| from urllib.parse import urlparse | |
| from pydantic import ( | |
| AnyHttpUrl, | |
| BaseModel, | |
| ConfigDict, | |
| Field, | |
| PrivateAttr, | |
| TypeAdapter, | |
| ValidationError, | |
| ValidationInfo, | |
| field_validator, | |
| ) | |
| from typing_extensions import Protocol | |
| import horizon | |
| from horizon.client.auth.base import BaseAuth # noqa: TC001 | |
| from horizon.commons.errors import get_response_for_status_code | |
| from horizon.commons.errors.base import APIErrorSchema | |
| logger = logging.getLogger(__name__) | |
| SessionClass = TypeVar("SessionClass") | |
| ResponseSchema = TypeVar("ResponseSchema", bound=BaseModel) | |
| class BaseResponse(Protocol): | |
| """Response-like object. Same interface is shared between requests.Response and httpx.Response""" | |
| def status_code(self) -> int: ... | |
| def content(self) -> Any: ... | |
| def json(self) -> Any: ... | |
| def raise_for_status(self) -> None: ... | |
| def headers(self) -> dict[str, str]: ... | |
| class BaseClient(BaseModel, Generic[SessionClass]): | |
| """Base Horizon client implementation, designed to be subclassed""" | |
| base_url: AnyHttpUrl | |
| auth: BaseAuth | |
| session: SessionClass | None = Field(default=None, validate_default=True) | |
| _backend_version_tuple: tuple[int, ...] = PrivateAttr(default_factory=tuple) | |
| model_config = ConfigDict(arbitrary_types_allowed=True) | |
| def session_class(cls) -> type[SessionClass]: | |
| # Get `Session` from `SyncClient(BaseClient[Session])` | |
| return cls.model_fields["session"].annotation.__args__[0] # type: ignore[union-attr] | |
| def _validate_url(cls, value: AnyHttpUrl): | |
| """`http://localhost:8000/` -> `http://localhost:8000`""" | |
| if value.path: | |
| return urlparse(str(value))._replace(path=value.path.rstrip("/")).geturl() | |
| return value | |
| def _default_session(cls, session: SessionClass | None): | |
| """If session is not passed, create it automatically""" | |
| if session: | |
| return session | |
| return cls.session_class()() | |
| def _patch_session(cls, session: SessionClass, info: ValidationInfo): | |
| """Patch session for chosen auth method, if required""" | |
| auth: BaseAuth = info.data["auth"] # type: ignore[assignment] | |
| return auth.patch_session(session) | |
| def _parse_body(self, body: dict, response_class: type[ResponseSchema]) -> ResponseSchema: | |
| try: | |
| return TypeAdapter(response_class).validate_python(body) | |
| except ValidationError as e: | |
| raise e from ValueError(body) | |
| def _handle_backend_version(self, backend_version: str | None): | |
| if self._backend_version_tuple or not backend_version: | |
| return | |
| self._backend_version_tuple = tuple(map(int, backend_version.split("."))) | |
| if self._backend_version_tuple > horizon.__version_tuple__: | |
| message = ( | |
| f"Horizon client version {horizon.__version__!r} does not match backend version {backend_version!r}. " | |
| "Please upgrade." | |
| ) | |
| warnings.warn(message, UserWarning, stacklevel=6) | |
| def _handle_response( # noqa: C901 | |
| self, | |
| response: BaseResponse, | |
| response_class: type[ResponseSchema] | None, | |
| ) -> ResponseSchema | None: | |
| """Convert Response object to expected response class, or raise an exception matching the status code""" | |
| request_id: str | None = response.headers.get("X-Request-ID", None) | |
| if request_id: | |
| logger.debug("Request ID: %r", request_id) | |
| backend_version = response.headers.get("X-Application-Version", None) | |
| self._handle_backend_version(backend_version) | |
| if response.status_code == http.HTTPStatus.NO_CONTENT.value: | |
| return None | |
| if response.status_code < http.HTTPStatus.BAD_REQUEST.value and response_class: | |
| return self._parse_body(response.json(), response_class) | |
| # raise_for_exception will definitely raise something, but mypy does not know that | |
| # so we create some exception to be bypass it | |
| http_exception: Exception = AssertionError("If you see this message, something went wrong") | |
| try: | |
| response.raise_for_status() | |
| except Exception as e: # noqa: BLE001 | |
| http_exception = e | |
| if request_id and hasattr(http_exception, "add_note"): | |
| # add_note is only available in Python 3.11+ | |
| # https://docs.python.org/3/library/exceptions.html#BaseException.add_note | |
| http_exception.add_note(f"Request ID: {request_id!r}") | |
| try: | |
| body = response.json() | |
| if hasattr(http_exception, "add_note"): | |
| http_exception.add_note(f"Response body:\n{pprint.pformat(body)}") | |
| except Exception as format_err: | |
| if hasattr(http_exception, "add_note"): | |
| http_exception.add_note(f"Response body:\n{response.content!r}") | |
| else: | |
| logger.error("Response body:\n%r", response.content) # noqa: TRY400 | |
| raise format_err from http_exception | |
| error_response = get_response_for_status_code(response.status_code) | |
| if not error_response: | |
| # cannot handle this status code | |
| raise http_exception | |
| try: | |
| error_value = APIErrorSchema[error_response.schema].model_validate(body) # type: ignore[name-defined] | |
| except ValidationError: | |
| # Something wrong with API response, probably wrong URL | |
| raise http_exception # noqa: B904 | |
| get_exception = getattr(error_value.error, "to_exception", None) | |
| if get_exception: | |
| raise get_exception() from http_exception | |
| raise http_exception | |
Xet Storage Details
- Size:
- 6.11 kB
- Xet hash:
- 3e1417d07d4037d7c95a8613c7922cbe9cd1840764572eef2aaff5d34efecf68
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.