[PYTHON] Access the Docker Remote API with Requests

Overview

I want to use Docker Remote API from Python Requests. It can be used from TCP if it is encrypted, but since we are thinking of using the API from the same host, we use unix socket.

Reading and writing Unix sockets

The Docker socket file is in /var/run/docker.sock. Reading and writing socket files is as follows.

import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/var/run/docker.sock")
# s.recv, s.send, etc.

Use your own socket with Requests

This is quite annoying and you need to implement Transport Adapter. And for that purpose, it is necessary to implement PoolManager, HTTPConnectionPool, and HTTPConnection together.

import socket
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3 import PoolManager, HTTPConnectionPool
from httplib import HTTPConnection

class MyAdapter(HTTPAdapter):

    def __init__(self, sockfile, **kwargs):
        self._sockfile = sockfile
        super(MyAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, **kwargs):
        self.poolmanager = MyPoolManager(self._sockfile,
                                         num_pools=connections, maxsize=maxsize)


class MyPoolManager(PoolManager):

    def __init__(self, sockfile, **kwargs):
        self._sockfile = sockfile
        super(MyPoolManager, self).__init__(**kwargs)

    def _new_pool(self, scheme, host, port):
        return MyConnectionPool(self._sockfile, host, port, **self.connection_pool_kw)


class MyConnectionPool(HTTPConnectionPool):

    def __init__(self, sockfile, host, port, **kwargs):
        self._sockfile = sockfile
        super(MyConnectionPool, self).__init__(host, port, **kwargs)

    def _new_conn(self):
        self.num_connections += 1
        return MyConnection(self._sockfile,
                            host=self.host, port=self.port, strict=self.strict)
   
   
class MyConnection(HTTPConnection):

    def __init__(self, sockfile, **kwargs):
        self._sockfile = sockfile
        HTTPConnection.__init__(self, **kwargs)

    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.connect(self._sockfile)

        if self._tunnel_host:
            self._tunnel()

Note that HTTPConnection is an old-style class, so be careful about the initialization method.

Use of API

The usage example is as follows.

req = requests.Session()
req.mount("http://", MyAdapter("/var/run/docker.sock"))
print req.get("http://127.0.0.1/images/json?all=0").json()

The place where it is written as http://127.0.0.1 is not good ...

reference

Recommended Posts

Access the Docker Remote API with Requests
Call the API with python3.
Specifying the date with the Twitter API
Get the weather with Python requests
Get the weather with Python requests 2
Hit the Etherpad-lite API with Python
Access the Twitter API in Python
Grant an access token with the curl command and POST the API
Run the IDCF cloud CLI with Docker
Behind the flyer: Using Docker with Python
Get holidays with the Google Calendar API
Play with puns using the COTOHA API
Log in to the remote server with SSH
Tweet regularly with the Go language Twitter API
Note: Prepare the environment of CmdStanPy with docker
Prepare the execution environment of Python3 with Docker
Hit the Web API using requests Example: Flickr
Until you use the Kaggle API with Colab
Use the Kaggle API inside a Docker container
Get an access token for the Pocket API
Access a site with client certificate authentication with Requests
It's too easy to access the Twitter API with rauth and I have her ...
Play with the power usage API provided by Yahoo
Change the time zone with Docker in Oracle Database
Hit the Twitter API after Oauth authentication with Django
[Boto3] Search for Cognito users with the List Users API
Register a ticket with redmine API using python requests
Create a tweet heatmap with the Google Maps API
Pepper-kun remote control environment construction with Docker + IPython Notebook
Get comments and subscribers with the YouTube Data API
Preparing the execution environment of PyTorch with Docker November 2019
Note calling the CUDA Driver API with Python ctypes
I moved the automatic summarization API "summpy" with python3.
I tried hitting the API with echonest's python client
Tftp server with Docker
[No venv required] The strongest Python development environment created with Remote Containers [VS Code / Docker]
Gurunavi API access method
I made an API with Docker that returns the predicted value of the machine learning model
Use python with docker
Extrude with Fusion360 API
Proxy server with Docker
Hello, World with Docker
Retry with python requests
Try hitting the Twitter API quickly and easily with Python
Specify the project name of docker-compose with Docker integration of Pycharm
A note about hitting the Facebook API with the Python SDK
Access the C structure field with the name reserved in Go.
The first API to make with python Djnago REST framework
Access the file with a relative path from the execution script.
Access the host SQL Server with python27 / pyodbc on the container
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
Throw appointments to others with the LINE WORKS calendar API
Streamline information gathering with the Twitter API and Slack bots
I tried saving the DRF API request history with django-request
When you access the web server, L Chika with Arduino
Get the host name of the host PC with Docker on Linux
Until API made with Flask + MySQL is converted to Docker