requests-unixsocket
requests-unixsocket is a Python library that allows the popular `requests` HTTP library to communicate over UNIX domain sockets. It extends `requests`' functionality to support `http+unix://` URLs. The current stable version is 0.4.1. Releases appear to be infrequent, focusing on maintenance and compatibility with newer `requests` versions.
Warnings
- breaking Updates to the upstream `requests` library can sometimes introduce breaking changes that affect `requests-unixsocket`, particularly related to internal adapter interfaces. While `requests-unixsocket` aims to maintain compatibility, rapid `requests` releases may temporarily break functionality.
- gotcha UNIX socket paths in URLs must be URL-percent-encoded (e.g., `/var/run/docker.sock` becomes `%2Fvar%2Frun%2Fdocker.sock`). Failure to encode correctly will result in incorrect URL parsing and connection errors.
- gotcha Using `requests_unixsocket.monkeypatch()` globally alters the default behavior of `requests.get()` and `requests.Session()` (for default sessions). This can lead to unexpected side effects in other parts of an application or library that rely on standard `requests` behavior.
- gotcha The default timeout for `requests-unixsocket` connections (historically 60 seconds) might differ from the default behavior of `requests` (which has no default timeout). This can lead to unexpected blocking or timeout behavior if not explicitly set.
- gotcha Abstract namespace sockets (e.g., `http+unix://\0test_socket/`) are a Linux-specific feature and will not work on other operating systems like macOS or Windows.
Install
-
pip install requests-unixsocket
Imports
- Session
from requests_unixsocket import Session
- monkeypatch
import requests_unixsocket; requests_unixsocket.monkeypatch()
Quickstart
import requests_unixsocket
import os
# Example for Docker daemon socket (adjust path if needed)
docker_socket_path = '/var/run/docker.sock' # or os.environ.get('DOCKER_SOCKET', '/var/run/docker.sock')
# Ensure the socket path exists for a runnable example
# In a real scenario, Docker or another service would create this.
# For this quickstart, we'll just check if it exists or use a dummy.
if not os.path.exists(docker_socket_path):
print(f"Warning: Docker socket not found at {docker_socket_path}. Quickstart might not connect.")
# Fallback to a non-existent path for structure, but it will fail.
docker_socket_path = '/tmp/nonexistent_socket.sock'
# Explicit Session usage
session = requests_unixsocket.Session()
# The socket path must be percent-encoded in the URL host part
encoded_socket_path = requests_unixsocket.requests.compat.quote_plus(docker_socket_path)
url = f'http+unix://{encoded_socket_path}/info'
try:
response = session.get(url, timeout=5)
response.raise_for_status() # Raise an exception for HTTP errors
print("Explicit Session usage successful!")
print(f"Status Code: {response.status_code}")
print(f"JSON Response Keys: {list(response.json().keys())[:5]}...")
except requests_unixsocket.requests.exceptions.ConnectionError as e:
print(f"Connection Error: Could not connect to UNIX socket at {docker_socket_path}. Is a service listening there? (Error: {e})")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# --- Alternative: Monkeypatching (affects global requests behavior) ---
# This is generally discouraged for libraries, but shown for completeness.
# with requests_unixsocket.monkeypatch():
# try:
# response_mp = requests_unixsocket.requests.get(url, timeout=5)
# response_mp.raise_for_status()
# print("\nMonkeypatching usage successful!")
# print(f"Status Code: {response_mp.status_code}")
# print(f"JSON Response Keys: {list(response_mp.json().keys())[:5]}...")
# except requests_unixsocket.requests.exceptions.ConnectionError as e:
# print(f"\nMonkeypatching Connection Error: Could not connect to UNIX socket at {docker_socket_path}. (Error: {e})")
# except Exception as e:
# print(f"\nAn unexpected error occurred with monkeypatching: {e}")