0
# requests-unixsocket
1
2
A Python library that enables HTTP communication over UNIX domain sockets using the familiar requests API. It extends the popular requests library to support UNIX socket connections, making it ideal for communicating with local services like Docker daemons, uWSGI servers, and other socket-based services.
3
4
## Package Information
5
6
- **Package Name**: requests-unixsocket
7
- **Language**: Python
8
- **Installation**: `pip install requests-unixsocket`
9
- **Dependencies**: requests >= 1.1
10
11
## Core Imports
12
13
```python
14
import requests_unixsocket
15
```
16
17
For specific components:
18
19
```python
20
from requests_unixsocket import Session, monkeypatch, UnixAdapter
21
```
22
23
For testing utilities:
24
25
```python
26
from requests_unixsocket.testutils import UnixSocketServerThread
27
```
28
29
## Basic Usage
30
31
### Using Session Class (Explicit)
32
33
```python
34
import requests_unixsocket
35
36
# Create a session configured for UNIX socket communication
37
session = requests_unixsocket.Session()
38
39
# Make HTTP requests to a UNIX socket (Docker daemon example)
40
response = session.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/info')
41
print(response.json())
42
43
# Support for all HTTP methods
44
response = session.post('http+unix://%2Fvar%2Frun%2Fdocker.sock/containers/create',
45
json={'Image': 'nginx'})
46
```
47
48
### Using Monkeypatch (Implicit)
49
50
```python
51
import requests
52
import requests_unixsocket
53
54
# Temporarily patch the global requests module
55
with requests_unixsocket.monkeypatch():
56
response = requests.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/info')
57
print(response.status_code)
58
```
59
60
### Abstract Namespace Sockets (Linux)
61
62
```python
63
import requests_unixsocket
64
65
session = requests_unixsocket.Session()
66
67
# Use \0 prefix for abstract namespace sockets
68
response = session.get('http+unix://\0test_socket/api/status')
69
print(response.text)
70
```
71
72
## URL Format
73
74
UNIX socket URLs use the `http+unix://` scheme with percent-encoded socket paths:
75
76
- Regular socket: `http+unix://%2Ftmp%2Fsocket.sock/path/to/endpoint`
77
- Abstract namespace (Linux): `http+unix://\0socket_name/path/to/endpoint`
78
79
The socket path is percent-encoded, and the HTTP path follows after the socket specification.
80
81
## Architecture
82
83
The library provides multiple interface layers for different use cases:
84
85
- **Session Layer**: High-level `Session` class that extends `requests.Session` with UNIX socket support. Provides the most familiar API for users already using requests.
86
- **Function Layer**: Module-level HTTP functions (`get`, `post`, etc.) that work like their requests counterparts but support UNIX sockets.
87
- **Monkeypatch Layer**: `monkeypatch` class that temporarily or permanently modifies the global requests module to support UNIX sockets, allowing existing code to work unchanged.
88
- **Adapter Layer**: Low-level `UnixAdapter` class that handles the actual UNIX socket connections. Can be used directly for custom session configurations.
89
- **Testing Layer**: `UnixSocketServerThread` utility for creating test servers on UNIX sockets.
90
91
This layered design allows the library to support everything from drop-in compatibility (via monkeypatching) to fine-grained control (via direct adapter usage).
92
93
## Capabilities
94
95
### Session Class
96
97
Provides a requests-compatible session for UNIX socket communication.
98
99
```python { .api }
100
class Session(requests.Session):
101
def __init__(self, url_scheme=DEFAULT_SCHEME, *args, **kwargs):
102
"""
103
Create a session configured for UNIX socket HTTP communication.
104
105
Parameters:
106
- url_scheme: str, URL scheme to mount the adapter for (default: 'http+unix://')
107
- *args, **kwargs: Additional arguments passed to requests.Session
108
109
Inherits all methods from requests.Session:
110
- get(url, **kwargs): Make GET request
111
- post(url, data=None, json=None, **kwargs): Make POST request
112
- put(url, data=None, **kwargs): Make PUT request
113
- patch(url, data=None, **kwargs): Make PATCH request
114
- delete(url, **kwargs): Make DELETE request
115
- head(url, **kwargs): Make HEAD request
116
- options(url, **kwargs): Make OPTIONS request
117
- request(method, url, **kwargs): Make request with specified method
118
"""
119
```
120
121
### Monkeypatch
122
123
Patches the global requests module to support UNIX sockets, either temporarily (as context manager) or globally (as function call).
124
125
```python { .api }
126
class monkeypatch:
127
def __init__(self, url_scheme=DEFAULT_SCHEME):
128
"""
129
Patches global requests module to support UNIX sockets.
130
Can be used as context manager or called directly for global patching.
131
132
Parameters:
133
- url_scheme: str, URL scheme to handle (default: 'http+unix://')
134
135
Usage patterns:
136
1. Context manager (temporary): with requests_unixsocket.monkeypatch():
137
2. Function call (global): requests_unixsocket.monkeypatch()
138
"""
139
140
def __enter__(self):
141
"""Enter context manager, patches global requests functions."""
142
143
def __exit__(self, *args):
144
"""Exit context manager, restores original requests functions."""
145
```
146
147
### HTTP Method Functions
148
149
Module-level functions that work like their requests counterparts but support UNIX sockets.
150
151
```python { .api }
152
def request(method, url, **kwargs):
153
"""
154
Make HTTP request to UNIX socket.
155
156
Parameters:
157
- method: str, HTTP method ('GET', 'POST', etc.)
158
- url: str, UNIX socket URL with http+unix:// scheme
159
- **kwargs: Additional arguments passed to requests
160
161
Returns:
162
requests.Response object
163
"""
164
165
def get(url, **kwargs):
166
"""
167
Make GET request to UNIX socket.
168
169
Parameters:
170
- url: str, UNIX socket URL
171
- **kwargs: Additional arguments (allow_redirects=True by default)
172
173
Returns:
174
requests.Response object
175
"""
176
177
def post(url, data=None, json=None, **kwargs):
178
"""
179
Make POST request to UNIX socket.
180
181
Parameters:
182
- url: str, UNIX socket URL
183
- data: dict/bytes/file-like, request body data
184
- json: dict, JSON data to send in body
185
- **kwargs: Additional arguments
186
187
Returns:
188
requests.Response object
189
"""
190
191
def put(url, data=None, **kwargs):
192
"""
193
Make PUT request to UNIX socket.
194
195
Parameters:
196
- url: str, UNIX socket URL
197
- data: dict/bytes/file-like, request body data
198
- **kwargs: Additional arguments
199
200
Returns:
201
requests.Response object
202
"""
203
204
def patch(url, data=None, **kwargs):
205
"""
206
Make PATCH request to UNIX socket.
207
208
Parameters:
209
- url: str, UNIX socket URL
210
- data: dict/bytes/file-like, request body data
211
- **kwargs: Additional arguments
212
213
Returns:
214
requests.Response object
215
"""
216
217
def delete(url, **kwargs):
218
"""
219
Make DELETE request to UNIX socket.
220
221
Parameters:
222
- url: str, UNIX socket URL
223
- **kwargs: Additional arguments
224
225
Returns:
226
requests.Response object
227
"""
228
229
def head(url, **kwargs):
230
"""
231
Make HEAD request to UNIX socket.
232
233
Parameters:
234
- url: str, UNIX socket URL
235
- **kwargs: Additional arguments (allow_redirects=False by default)
236
237
Returns:
238
requests.Response object
239
"""
240
241
def options(url, **kwargs):
242
"""
243
Make OPTIONS request to UNIX socket.
244
245
Parameters:
246
- url: str, UNIX socket URL
247
- **kwargs: Additional arguments (allow_redirects=True by default)
248
249
Returns:
250
requests.Response object
251
"""
252
```
253
254
### UnixAdapter
255
256
Low-level HTTP adapter for UNIX socket connections.
257
258
```python { .api }
259
class UnixAdapter(requests.adapters.HTTPAdapter):
260
def __init__(self, timeout=60, pool_connections=25, *args, **kwargs):
261
"""
262
HTTP adapter for UNIX domain socket connections.
263
264
Parameters:
265
- timeout: int, connection timeout in seconds (default: 60)
266
- pool_connections: int, number of connection pools to cache (default: 25)
267
- *args, **kwargs: Additional arguments passed to HTTPAdapter
268
"""
269
270
def get_connection(self, url, proxies=None):
271
"""
272
Get connection pool for the given URL.
273
274
Parameters:
275
- url: str, UNIX socket URL
276
- proxies: dict, proxy configuration (not supported, will raise ValueError)
277
278
Returns:
279
UnixHTTPConnectionPool instance
280
281
Raises:
282
ValueError: If proxies are specified
283
"""
284
285
def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
286
"""
287
Get connection with TLS context (compatibility method for requests 2.32.2+).
288
289
Parameters:
290
- request: PreparedRequest object
291
- verify: bool/str, SSL verification settings
292
- proxies: dict, proxy configuration (not supported)
293
- cert: SSL client certificate
294
295
Returns:
296
Connection pool
297
"""
298
299
def request_url(self, request, proxies):
300
"""
301
Extract path portion from request URL for UNIX socket communication.
302
303
Parameters:
304
- request: PreparedRequest object
305
- proxies: dict, proxy configuration
306
307
Returns:
308
str: Path portion of the URL
309
"""
310
311
def close(self):
312
"""Close all connection pools and clean up resources."""
313
```
314
315
### Testing Utilities
316
317
#### UnixSocketServerThread
318
319
Test server that creates an HTTP server listening on a UNIX socket.
320
321
```python { .api }
322
class UnixSocketServerThread(threading.Thread):
323
def __init__(self, *args, **kwargs):
324
"""
325
Creates a test HTTP server on a temporary UNIX socket.
326
327
Attributes:
328
- usock: str, path to the created UNIX socket
329
"""
330
331
def run(self):
332
"""Start the server thread (called automatically by threading)."""
333
334
def __enter__(self):
335
"""
336
Enter context manager, starts server and waits for it to be ready.
337
338
Returns:
339
self: The server thread instance
340
"""
341
342
def __exit__(self, *args):
343
"""Exit context manager, stops and cleans up the server."""
344
```
345
346
### Constants
347
348
```python { .api }
349
DEFAULT_SCHEME: str
350
# Default URL scheme: 'http+unix://'
351
```
352
353
## Error Handling
354
355
The library raises standard requests exceptions:
356
357
- **requests.ConnectionError**: When unable to connect to the UNIX socket
358
- **ValueError**: When proxies are specified (not supported)
359
- **requests.exceptions.InvalidSchema**: When using unsupported URL schemes
360
361
All other requests exceptions (Timeout, HTTPError, etc.) behave normally.
362
363
## Usage Examples
364
365
### Docker API Communication
366
367
```python
368
import requests_unixsocket
369
import json
370
371
session = requests_unixsocket.Session()
372
373
# Get Docker system information
374
response = session.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/info')
375
info = response.json()
376
print(f"Docker version: {info['ServerVersion']}")
377
378
# List containers
379
response = session.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/containers/json')
380
containers = response.json()
381
print(f"Running containers: {len(containers)}")
382
```
383
384
### Testing with UnixSocketServerThread
385
386
```python
387
import requests_unixsocket
388
from requests_unixsocket.testutils import UnixSocketServerThread
389
390
# Create a test server
391
with UnixSocketServerThread() as server:
392
session = requests_unixsocket.Session()
393
394
# URL-encode the socket path
395
import requests.compat
396
socket_path = requests.compat.quote_plus(server.usock)
397
url = f'http+unix://{socket_path}/test/endpoint'
398
399
# Make request to test server
400
response = session.get(url)
401
assert response.status_code == 200
402
print(response.text) # "Hello world!"
403
```
404
405
### Global Monkeypatch
406
407
```python
408
import requests
409
import requests_unixsocket
410
411
# Patch globally (affects all requests in the application)
412
requests_unixsocket.monkeypatch()
413
414
# Now regular requests functions work with UNIX sockets
415
response = requests.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/info')
416
print(response.status_code) # 200
417
418
# All requests module functions now support UNIX sockets
419
response = requests.post('http+unix://%2Ftmp%2Fapp.sock/api/data',
420
json={'key': 'value'})
421
print(response.json())
422
```
423
424
## Platform Support
425
426
- **UNIX domain sockets**: Supported on all UNIX-like systems (Linux, macOS, BSD)
427
- **Abstract namespace sockets**: Linux only (use `\0` prefix)
428
- **Python versions**: 3.9+