<p>Giving the port forward object</p>
<pre><code>from kubernetes.stream import stream, portforward


    pf = portforward(
         k8s_client_v1.connect_get_namespaced_pod_portforward,
         pod_name,
         name_space,
         ports=port
    )
    
    pf.socket(port)
</code></pre>
<p><code>pf</code> is a socket object from <code>AF_UNIX</code> family.</p>
<p>I need a better understating whether another <code>AF_INET</code> family socket has to be instantiated in oder to achieve the same functionality as <code>kubectl</code> client has, ex: <code>kubectl port-forward $pod_name $port</code></p>
<p>I appreciate in advance if someone could share any snippets of this type of implementation.</p>
<p>At this moment creating port forward object was inspired from <a href="https://github.com/kubernetes-client/python/blob/master/examples/pod_portforward.py#L176" rel="nofollow noreferrer">here</a></p>

<p>I am not an expert on sockets, but I managed to wrap the socket from the port forwarding with a <code>http.client.HTTPConnection</code>. I wanted to patch <code>requests</code>, but I could not make it work.</p>
<p>Anyway, this way the http requests can be implemented more conveniently in a high level fashion. Not sure if you were looking for that, but I was. To query pod names, ports and more you can check the <a href="https://v1-17.docs.kubernetes.io/docs/reference/generated/kubernetes-api/v1.17" rel="nofollow noreferrer">api reference</a> for kubernetes and look up the corresponding method in the python package.</p>
<pre><code>from http.client import HTTPConnection
from kubernetes import client, config
from kubernetes.stream import portforward
from kubernetes.stream.ws_client import PortForward

class ForwardedKubernetesHTTPConnection(HTTPConnection):

    def __init__(self, forwarding: PortForward, port: int):
        super().__init__(&quot;127.0.0.1&quot;, port)
        self.sock = forwarding.socket(port)

    def connect(self) -&gt; None:
        pass

    def close(self) -&gt; None:
        pass

if __name__ == &quot;__main__&quot;:
    config.load_kube_config()
    client_v1 = client.CoreV1Api()
    name_space = &quot;my-namespace&quot;  # or get from api somehow
    pod_name = &quot;my-pod&quot;  # or get from api somehow
    port = 80
    
    pf = portforward(
        client_v1.connect_get_namespaced_pod_portforward,
        pod_name,
        name_space,
        ports=str(port)
    )

    conn = ForwardedKubernetesHTTPConnection(pf, port)
    conn.request(&quot;GET&quot;, &quot;/my/url&quot;)  # will fail for other methods
    resp = conn.getresponse()
    print(resp.status)
    print(resp.headers)
    print(resp.read())

    conn.request(&quot;GET&quot;, &quot;/my/other/url&quot;)
    # ...
</code></pre>
