Skip to content

Http

HTTP connections with various methods.

ApiKeyConnectionMethod

Bases: BareConnectionMethod

API key connection method.

Source code in teledetection/sdk/http.py
class ApiKeyConnectionMethod(BareConnectionMethod):
    """API key connection method."""

    api_key: ApiKey

    def get_headers(self):
        """Return the headers."""
        return self.api_key.to_dict()

get_headers()

Return the headers.

Source code in teledetection/sdk/http.py
def get_headers(self):
    """Return the headers."""
    return self.api_key.to_dict()

BareConnectionMethod

Bases: BaseModel

Bare connection method, no extra headers.

Source code in teledetection/sdk/http.py
class BareConnectionMethod(BaseModel):
    """Bare connection method, no extra headers."""

    model_config = ConfigDict(arbitrary_types_allowed=True)
    endpoint: str = ENV.tld_signing_endpoint

    def get_headers(self) -> Dict[str, str]:
        """Get the headers."""
        return {}

get_headers()

Get the headers.

Source code in teledetection/sdk/http.py
def get_headers(self) -> Dict[str, str]:
    """Get the headers."""
    return {}

HTTPSession

HTTP session class.

Source code in teledetection/sdk/http.py
class HTTPSession:
    """HTTP session class."""

    def __init__(self):
        """Initialize the HTTP session."""
        self.session = create_session()
        self.timeout = TIMEOUT
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
        }
        self._method = None

    def get_method(self):
        """Get method."""
        log.debug("Get method")
        if not self._method:
            # Lazy instantiation
            self.prepare_connection_method()
        return self._method

    def prepare_connection_method(self):
        """Set the connection method."""
        # Custom server without authentication method
        if ENV.tld_disable_auth:
            self._method = BareConnectionMethod(endpoint=ENV.tld_signing_endpoint)

        # API key method
        elif api_key := ApiKey.grab():
            self._method = ApiKeyConnectionMethod(
                endpoint=ENV.tld_signing_endpoint, api_key=api_key
            )

        # OAuth2 method
        else:
            self._method = OAuth2ConnectionMethod(endpoint=ENV.tld_signing_endpoint)

    def post(self, route: str, params: Dict):
        """Perform a POST request."""
        method = self.get_method()
        url = f"{method.endpoint}{route}"
        headers = {**self.headers, **method.get_headers()}
        log.debug("POST to %s", url)
        response = self.session.post(url, json=params, headers=headers, timeout=TIMEOUT)
        try:
            response.raise_for_status()
        except Exception as e:
            log.error(literal_eval(response.text))
            raise e

        return response

__init__()

Initialize the HTTP session.

Source code in teledetection/sdk/http.py
def __init__(self):
    """Initialize the HTTP session."""
    self.session = create_session()
    self.timeout = TIMEOUT
    self.headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    self._method = None

get_method()

Get method.

Source code in teledetection/sdk/http.py
def get_method(self):
    """Get method."""
    log.debug("Get method")
    if not self._method:
        # Lazy instantiation
        self.prepare_connection_method()
    return self._method

post(route, params)

Perform a POST request.

Source code in teledetection/sdk/http.py
def post(self, route: str, params: Dict):
    """Perform a POST request."""
    method = self.get_method()
    url = f"{method.endpoint}{route}"
    headers = {**self.headers, **method.get_headers()}
    log.debug("POST to %s", url)
    response = self.session.post(url, json=params, headers=headers, timeout=TIMEOUT)
    try:
        response.raise_for_status()
    except Exception as e:
        log.error(literal_eval(response.text))
        raise e

    return response

prepare_connection_method()

Set the connection method.

Source code in teledetection/sdk/http.py
def prepare_connection_method(self):
    """Set the connection method."""
    # Custom server without authentication method
    if ENV.tld_disable_auth:
        self._method = BareConnectionMethod(endpoint=ENV.tld_signing_endpoint)

    # API key method
    elif api_key := ApiKey.grab():
        self._method = ApiKeyConnectionMethod(
            endpoint=ENV.tld_signing_endpoint, api_key=api_key
        )

    # OAuth2 method
    else:
        self._method = OAuth2ConnectionMethod(endpoint=ENV.tld_signing_endpoint)

OAuth2ConnectionMethod

Bases: BareConnectionMethod

OAuth2 connection method.

Source code in teledetection/sdk/http.py
class OAuth2ConnectionMethod(BareConnectionMethod):
    """OAuth2 connection method."""

    oauth2_session: OAuth2Session = OAuth2Session()

    def get_headers(self):
        """Return the headers."""
        return {"authorization": f"bearer {self.oauth2_session.get_access_token()}"}

    def get_userinfo(self):
        """Override parent method from BareConnectionMethod."""
        openapi_url = retrieve_token_endpoint().replace("/token", "/userinfo")
        return (
            create_session()
            .get(openapi_url, timeout=TIMEOUT, headers=self.get_headers())
            .json()
        )

get_headers()

Return the headers.

Source code in teledetection/sdk/http.py
def get_headers(self):
    """Return the headers."""
    return {"authorization": f"bearer {self.oauth2_session.get_access_token()}"}

get_userinfo()

Override parent method from BareConnectionMethod.

Source code in teledetection/sdk/http.py
def get_userinfo(self):
    """Override parent method from BareConnectionMethod."""
    openapi_url = retrieve_token_endpoint().replace("/token", "/userinfo")
    return (
        create_session()
        .get(openapi_url, timeout=TIMEOUT, headers=self.get_headers())
        .json()
    )

get_headers()

Return the headers needed to authenticate on the system.

Source code in teledetection/sdk/http.py
def get_headers() -> dict[str, Any]:
    """Return the headers needed to authenticate on the system."""
    return session.get_method().get_headers()

get_userinfo()

Return userinfo.

Source code in teledetection/sdk/http.py
def get_userinfo() -> dict[str, str]:
    """Return userinfo."""
    return OAuth2ConnectionMethod().get_userinfo()

get_username()

Return username.

Source code in teledetection/sdk/http.py
def get_username() -> str:
    """Return username."""
    user_info = get_userinfo()
    assert user_info, "Could not fetch user info"
    return user_info["preferred_username"]