Untitled

 avatar
unknown
python
a year ago
1.0 kB
17
Indexable
from __future__ import annotations

import json
from http.client import HTTPConnection, HTTPResponse, HTTPSConnection
from typing import Any, Protocol, TypeAlias

HTTPResponseDictType: TypeAlias = dict[str, Any]


class ConnectionProtocol(Protocol):
    def getresponse(self) -> HTTPResponse:
        pass

    def close(self) -> None:
        pass


class ConnectionMixin:
    def response_dump(self: ConnectionProtocol) -> HTTPResponseDictType:
        return json.loads(self.getresponse().read())

    def response_bytes(self: ConnectionProtocol) -> bytes:
        return self.getresponse().read()

    def __exit__(self: ConnectionProtocol, exc_type, exc_val, exc_tb) -> None:
        self.close()


class CustomHTTPConnection(
    ConnectionMixin,
    HTTPConnection
):
    def __enter__(self) -> CustomHTTPConnection:
        return self


class CustomHTTPSConnection(
    ConnectionMixin,
    HTTPSConnection
):
    def __enter__(self) -> CustomHTTPSConnection:
        return self
Editor is loading...
Leave a Comment