0
# V2 Enhanced API
1
2
Enhanced proxy implementations with improved error handling, SSL support, and additional configuration options. The V2 API provides the latest features and is recommended for new applications. Available for both synchronous and asynchronous usage patterns across multiple frameworks.
3
4
## V2 API Imports
5
6
```python
7
# Synchronous V2
8
from python_socks.sync.v2 import Proxy as SyncProxyV2, ProxyChain as SyncProxyChainV2
9
10
# Asyncio V2
11
from python_socks.async_.asyncio.v2 import Proxy as AsyncioProxyV2, ProxyChain as AsyncioProxyChainV2
12
13
# Trio V2
14
from python_socks.async_.trio.v2 import Proxy as TrioProxyV2, ProxyChain as TrioProxyChainV2
15
16
# AnyIO V2
17
from python_socks.async_.anyio.v2 import Proxy as AnyioProxyV2, ProxyChain as AnyioProxyChainV2
18
```
19
20
## Capabilities
21
22
### Synchronous V2 Proxy
23
24
Enhanced synchronous proxy with improved features and error handling.
25
26
```python { .api }
27
import ssl
28
from typing import Optional
29
30
class SyncProxy:
31
def __init__(
32
self,
33
proxy_type: ProxyType,
34
host: str,
35
port: int,
36
username: Optional[str] = None,
37
password: Optional[str] = None,
38
rdns: Optional[bool] = None,
39
proxy_ssl: Optional[ssl.SSLContext] = None,
40
forward: Optional['SyncProxy'] = None
41
): ...
42
43
def connect(
44
self,
45
dest_host: str,
46
dest_port: int,
47
dest_ssl: Optional[ssl.SSLContext] = None,
48
timeout: Optional[float] = None,
49
**kwargs
50
) -> 'SyncSocketStream': ...
51
52
@property
53
def proxy_host(self) -> str:
54
"""Get proxy host address."""
55
...
56
57
@property
58
def proxy_port(self) -> int:
59
"""Get proxy port number."""
60
...
61
62
@classmethod
63
def create(cls, *args, **kwargs) -> 'SyncProxy':
64
"""Create proxy instance (deprecated, use __init__ directly)."""
65
...
66
67
@classmethod
68
def from_url(cls, url: str, **kwargs) -> 'SyncProxy':
69
"""Create proxy instance from URL."""
70
...
71
```
72
73
**Enhanced Features:**
74
- Built-in SSL/TLS transport support via `proxy_ssl` and `dest_ssl` parameters
75
- Proxy chaining support with `forward` parameter
76
- Returns enhanced `SyncSocketStream` instead of raw socket
77
- Better error reporting and diagnostics
78
- Enhanced connection pooling compatibility
79
- Optimized performance characteristics
80
81
**V2-Specific Parameters:**
82
- `proxy_ssl`: Optional SSL context for connecting to the proxy server over TLS
83
- `forward`: Optional proxy to forward connections through (proxy chaining)
84
- `dest_ssl`: Optional SSL context for wrapping the destination connection
85
86
**Usage:**
87
88
```python
89
import ssl
90
from python_socks.sync.v2 import Proxy
91
92
# Create V2 proxy
93
proxy = Proxy.from_url('socks5://user:pass@proxy.example.com:1080')
94
95
# Connect with enhanced features
96
sock = proxy.connect('secure-api.example.com', 443, timeout=30)
97
98
# Enhanced SSL integration
99
context = ssl.create_default_context()
100
secure_sock = context.wrap_socket(
101
sock,
102
server_hostname='secure-api.example.com'
103
)
104
105
# Make secure request
106
request = b'GET /api/v1/data HTTP/1.1\r\nHost: secure-api.example.com\r\n\r\n'
107
secure_sock.send(request)
108
response = secure_sock.recv(4096)
109
secure_sock.close()
110
```
111
112
### SyncSocketStream Class
113
114
Enhanced socket wrapper returned by V2 proxy connections.
115
116
```python { .api }
117
class SyncSocketStream:
118
def __init__(self, sock: Union[socket.socket, ssl.SSLSocket]): ...
119
120
def write_all(self, data: bytes) -> None:
121
"""Write all data to the socket."""
122
...
123
124
def read(self, max_bytes: int = 65536) -> bytes:
125
"""Read up to max_bytes from the socket."""
126
...
127
128
def read_exact(self, n: int) -> bytes:
129
"""Read exactly n bytes from the socket."""
130
...
131
132
def close(self) -> None:
133
"""Close the underlying socket."""
134
...
135
136
@property
137
def socket(self) -> Union[socket.socket, ssl.SSLSocket]:
138
"""Get the underlying socket object."""
139
...
140
```
141
142
**SyncSocketStream Features:**
143
- Consistent interface across different socket types (plain, SSL, custom transports)
144
- Convenient methods for common I/O operations
145
- Better error handling and resource management
146
- Compatible with existing socket operations via `.socket` property
147
148
**Usage:**
149
150
```python
151
from python_socks.sync.v2 import Proxy
152
153
proxy = Proxy.from_url('socks5://proxy:1080')
154
stream = proxy.connect('example.com', 80)
155
156
# Use enhanced stream methods
157
stream.write_all(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
158
response = stream.read(4096)
159
160
# Or access underlying socket if needed
161
sock = stream.socket
162
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
163
164
stream.close()
165
```
166
167
### Synchronous V2 Proxy Chain
168
169
Enhanced proxy chaining with better error handling and performance.
170
171
```python { .api }
172
class ProxyChain:
173
def __init__(self, proxies: Iterable[SyncProxy]): ...
174
175
def connect(
176
self,
177
dest_host: str,
178
dest_port: int,
179
timeout: Optional[float] = None
180
) -> socket.socket: ...
181
```
182
183
**Enhanced Chain Features:**
184
- Better intermediate connection management
185
- Improved error propagation
186
- Enhanced timeout handling
187
- Optimized chain traversal
188
189
**Usage:**
190
191
```python
192
from python_socks.sync.v2 import Proxy, ProxyChain
193
194
# Create enhanced proxy chain
195
proxy1 = Proxy.from_url('socks5://first-proxy:1080')
196
proxy2 = Proxy.from_url('http://second-proxy:8080')
197
proxy3 = Proxy.from_url('socks4://third-proxy:1080')
198
199
chain = ProxyChain([proxy1, proxy2, proxy3])
200
201
# Connect through enhanced chain
202
sock = chain.connect('destination.example.com', 80, timeout=60)
203
204
# Use the connection
205
sock.send(b'GET / HTTP/1.1\r\nHost: destination.example.com\r\n\r\n')
206
response = sock.recv(4096)
207
print(response.decode())
208
sock.close()
209
```
210
211
### Asyncio V2 Proxy
212
213
Enhanced asyncio proxy implementation with advanced async features.
214
215
```python { .api }
216
class AsyncioProxy:
217
def __init__(
218
self,
219
proxy_type: ProxyType,
220
host: str,
221
port: int,
222
username: Optional[str] = None,
223
password: Optional[str] = None,
224
rdns: Optional[bool] = None,
225
loop: asyncio.AbstractEventLoop | None = None
226
): ...
227
228
async def connect(
229
self,
230
dest_host: str,
231
dest_port: int,
232
timeout: Optional[float] = None,
233
**kwargs
234
) -> socket.socket: ...
235
236
@classmethod
237
def create(cls, *args, **kwargs) -> 'AsyncioProxy': ...
238
239
@classmethod
240
def from_url(cls, url: str, **kwargs) -> 'AsyncioProxy': ...
241
```
242
243
**Enhanced Async Features:**
244
- Better cancellation support
245
- Improved timeout mechanisms
246
- Enhanced connection pooling
247
- Optimized for asyncio 3.11+ features
248
249
**Usage:**
250
251
```python
252
import asyncio
253
import ssl
254
from python_socks.async_.asyncio.v2 import Proxy
255
256
async def enhanced_async_example():
257
# Create V2 asyncio proxy
258
proxy = Proxy.from_url('socks5://proxy.example.com:1080')
259
260
# Enhanced async connect
261
sock = await proxy.connect('api.example.com', 443, timeout=30)
262
263
# Use with enhanced asyncio features
264
reader, writer = await asyncio.open_connection(
265
host=None,
266
port=None,
267
sock=sock,
268
ssl=ssl.create_default_context(),
269
server_hostname='api.example.com'
270
)
271
272
# Enhanced request handling
273
request = b'GET /v2/endpoint HTTP/1.1\r\nHost: api.example.com\r\n\r\n'
274
writer.write(request)
275
await writer.drain()
276
277
response = await reader.read(4096)
278
print(response.decode())
279
280
writer.close()
281
await writer.wait_closed()
282
283
asyncio.run(enhanced_async_example())
284
```
285
286
### Asyncio V2 Proxy Chain
287
288
Enhanced asynchronous proxy chaining for asyncio.
289
290
```python { .api }
291
class ProxyChain:
292
def __init__(self, proxies: Iterable[AsyncioProxy]): ...
293
294
async def connect(
295
self,
296
dest_host: str,
297
dest_port: int,
298
timeout: Optional[float] = None
299
) -> socket.socket: ...
300
```
301
302
**Usage:**
303
304
```python
305
import asyncio
306
from python_socks.async_.asyncio.v2 import Proxy, ProxyChain
307
308
async def enhanced_chain_example():
309
# Create enhanced async proxy chain
310
proxy1 = Proxy.from_url('socks5://proxy1.example.com:1080')
311
proxy2 = Proxy.from_url('http://proxy2.example.com:8080')
312
313
chain = ProxyChain([proxy1, proxy2])
314
315
# Enhanced async chain connection
316
sock = await chain.connect('destination.example.com', 80, timeout=45)
317
318
# Use the connection
319
reader, writer = await asyncio.open_connection(
320
host=None, port=None, sock=sock
321
)
322
323
writer.write(b'GET / HTTP/1.1\r\nHost: destination.example.com\r\n\r\n')
324
await writer.drain()
325
326
response = await reader.read(4096)
327
print(response.decode())
328
329
writer.close()
330
await writer.wait_closed()
331
332
asyncio.run(enhanced_chain_example())
333
```
334
335
### Trio V2 Proxy
336
337
Enhanced trio proxy implementation with structured concurrency improvements.
338
339
```python { .api }
340
class TrioProxy:
341
def __init__(
342
self,
343
proxy_type: ProxyType,
344
host: str,
345
port: int,
346
username: Optional[str] = None,
347
password: Optional[str] = None,
348
rdns: Optional[bool] = None
349
): ...
350
351
async def connect(
352
self,
353
dest_host: str,
354
dest_port: int,
355
timeout: Optional[float] = None,
356
**kwargs
357
) -> socket.socket: ...
358
359
@classmethod
360
def create(cls, *args, **kwargs) -> 'TrioProxy': ...
361
362
@classmethod
363
def from_url(cls, url: str, **kwargs) -> 'TrioProxy': ...
364
```
365
366
**Enhanced Trio Features:**
367
- Better structured concurrency integration
368
- Improved cancellation handling
369
- Enhanced memory management
370
- Optimized for trio's nursery patterns
371
372
**Usage:**
373
374
```python
375
import trio
376
import ssl
377
from python_socks.async_.trio.v2 import Proxy
378
379
async def enhanced_trio_example():
380
# Create V2 trio proxy
381
proxy = Proxy.from_url('socks5://proxy.example.com:1080')
382
383
# Enhanced trio connect
384
sock = await proxy.connect('secure-api.example.com', 443)
385
386
# Enhanced SSL integration with trio
387
ssl_context = ssl.create_default_context()
388
stream = trio.SSLStream(
389
trio.SocketStream(sock),
390
ssl_context,
391
server_hostname='secure-api.example.com'
392
)
393
394
# Make secure request
395
await stream.send_all(b'GET /api/data HTTP/1.1\r\nHost: secure-api.example.com\r\n\r\n')
396
response = await stream.receive_some(4096)
397
print(response.decode())
398
399
await stream.aclose()
400
401
trio.run(enhanced_trio_example)
402
```
403
404
### Trio V2 Proxy Chain
405
406
Enhanced proxy chaining for trio with better structured concurrency support.
407
408
```python { .api }
409
class ProxyChain:
410
def __init__(self, proxies: Iterable[TrioProxy]): ...
411
412
async def connect(
413
self,
414
dest_host: str,
415
dest_port: int,
416
timeout: Optional[float] = None
417
) -> socket.socket: ...
418
```
419
420
**Usage:**
421
422
```python
423
import trio
424
from python_socks.async_.trio.v2 import Proxy, ProxyChain
425
426
async def enhanced_trio_chain_example():
427
# Create enhanced trio proxy chain
428
proxy1 = Proxy.from_url('socks5://proxy1.example.com:1080')
429
proxy2 = Proxy.from_url('http://proxy2.example.com:8080')
430
431
chain = ProxyChain([proxy1, proxy2])
432
433
# Enhanced chain connection
434
sock = await chain.connect('example.com', 80)
435
436
# Use with trio streams
437
stream = trio.SocketStream(sock)
438
439
await stream.send_all(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
440
response = await stream.receive_some(4096)
441
print(response.decode())
442
443
await stream.aclose()
444
445
trio.run(enhanced_trio_chain_example)
446
```
447
448
### AnyIO V2 Proxy
449
450
Enhanced AnyIO proxy with cross-framework improvements.
451
452
```python { .api }
453
class AnyioProxy:
454
def __init__(
455
self,
456
proxy_type: ProxyType,
457
host: str,
458
port: int,
459
username: Optional[str] = None,
460
password: Optional[str] = None,
461
rdns: Optional[bool] = None
462
): ...
463
464
async def connect(
465
self,
466
dest_host: str,
467
dest_port: int,
468
timeout: Optional[float] = None,
469
**kwargs
470
) -> socket.socket: ...
471
472
@classmethod
473
def create(cls, *args, **kwargs) -> 'AnyioProxy': ...
474
475
@classmethod
476
def from_url(cls, url: str, **kwargs) -> 'AnyioProxy': ...
477
```
478
479
**Enhanced AnyIO Features:**
480
- Better cross-framework compatibility
481
- Improved backend detection
482
- Enhanced error handling across frameworks
483
- Optimized performance for all supported backends
484
485
**Usage:**
486
487
```python
488
import anyio
489
import ssl
490
from python_socks.async_.anyio.v2 import Proxy
491
492
async def enhanced_anyio_example():
493
# Create V2 AnyIO proxy
494
proxy = Proxy.from_url('socks5://proxy.example.com:1080')
495
496
# Enhanced cross-framework connect
497
sock = await proxy.connect('secure-api.example.com', 443)
498
499
# Enhanced SSL support across frameworks
500
ssl_context = ssl.create_default_context()
501
stream = await anyio.connect_tcp(
502
remote_host='secure-api.example.com',
503
remote_port=443,
504
sock=sock,
505
tls=True,
506
tls_hostname='secure-api.example.com'
507
)
508
509
# Make secure request
510
await stream.send(b'GET /v2/data HTTP/1.1\r\nHost: secure-api.example.com\r\n\r\n')
511
response = await stream.receive(4096)
512
print(response.decode())
513
514
await stream.aclose()
515
516
# Works with any supported backend
517
anyio.run(enhanced_anyio_example, backend='asyncio')
518
```
519
520
### AnyIO V2 Proxy Chain
521
522
Enhanced proxy chaining with cross-framework compatibility.
523
524
```python { .api }
525
class ProxyChain:
526
def __init__(self, proxies: Iterable[AnyioProxy]): ...
527
528
async def connect(
529
self,
530
dest_host: str,
531
dest_port: int,
532
timeout: Optional[float] = None
533
) -> socket.socket: ...
534
```
535
536
**Usage:**
537
538
```python
539
import anyio
540
from python_socks.async_.anyio.v2 import Proxy, ProxyChain
541
542
async def enhanced_anyio_chain_example():
543
# Create enhanced AnyIO proxy chain
544
proxy1 = Proxy.from_url('socks5://proxy1.example.com:1080')
545
proxy2 = Proxy.from_url('http://proxy2.example.com:8080')
546
547
chain = ProxyChain([proxy1, proxy2])
548
549
# Enhanced chain connection
550
sock = await chain.connect('api.example.com', 443)
551
552
# Cross-framework usage
553
stream = anyio.SocketStream(sock)
554
555
await stream.send(b'GET /api/v2/endpoint HTTP/1.1\r\nHost: api.example.com\r\n\r\n')
556
response = await stream.receive(4096)
557
print(response.decode())
558
559
await stream.aclose()
560
561
# Test with different backends
562
async def test_backends():
563
for backend in ['asyncio', 'trio']:
564
print(f"Testing with {backend}")
565
await anyio.run(enhanced_anyio_chain_example, backend=backend)
566
567
anyio.run(test_backends, backend='asyncio')
568
```
569
570
## V2 API Improvements
571
572
### Enhanced Error Handling
573
574
The V2 API provides more detailed error information and better error categorization:
575
576
```python
577
from python_socks import ProxyError
578
from python_socks.sync.v2 import Proxy
579
580
try:
581
proxy = Proxy.from_url('socks5://invalid-proxy:1080')
582
sock = proxy.connect('example.com', 80)
583
except ProxyError as e:
584
# V2 provides enhanced error details
585
print(f"Error: {e}")
586
print(f"Error code: {e.error_code}")
587
print(f"Protocol-specific info: {getattr(e, 'protocol_info', 'N/A')}")
588
```
589
590
### Performance Optimizations
591
592
V2 implementations include various performance improvements:
593
594
- Optimized connection establishment
595
- Better memory usage patterns
596
- Reduced syscall overhead
597
- Enhanced connection pooling support
598
599
### SSL/TLS Enhancements
600
601
Improved SSL/TLS support across all V2 implementations:
602
603
```python
604
import ssl
605
from python_socks.sync.v2 import Proxy
606
607
# Enhanced SSL configuration support
608
proxy = Proxy.from_url('socks5://proxy.example.com:1080')
609
sock = proxy.connect('secure-api.example.com', 443)
610
611
# V2 provides better SSL context integration
612
context = ssl.create_default_context()
613
context.check_hostname = True
614
context.verify_mode = ssl.CERT_REQUIRED
615
616
secure_sock = context.wrap_socket(
617
sock,
618
server_hostname='secure-api.example.com'
619
)
620
```
621
622
### Migration from V1 to V2
623
624
The V2 API maintains backward compatibility while adding enhancements:
625
626
```python
627
# V1 usage
628
from python_socks.sync import Proxy as ProxyV1
629
630
# V2 usage (recommended)
631
from python_socks.sync.v2 import Proxy as ProxyV2
632
633
# Same interface, enhanced implementation
634
proxy_v1 = ProxyV1.from_url('socks5://proxy.example.com:1080')
635
proxy_v2 = ProxyV2.from_url('socks5://proxy.example.com:1080')
636
637
# Both work the same way, V2 has better performance and features
638
sock_v1 = proxy_v1.connect('example.com', 80)
639
sock_v2 = proxy_v2.connect('example.com', 80) # Recommended
640
```
641
642
## V2 Best Practices
643
644
### Use V2 for New Applications
645
646
Always use V2 implementations for new projects:
647
648
```python
649
# Recommended imports for new applications
650
from python_socks.sync.v2 import Proxy, ProxyChain
651
from python_socks.async_.asyncio.v2 import Proxy as AsyncProxy
652
```
653
654
### Enhanced Connection Management
655
656
V2 provides better connection lifecycle management:
657
658
```python
659
from contextlib import asynccontextmanager
660
from python_socks.async_.asyncio.v2 import Proxy
661
662
@asynccontextmanager
663
async def proxy_connection_v2(proxy_url, dest_host, dest_port):
664
"""Enhanced V2 connection context manager."""
665
proxy = Proxy.from_url(proxy_url)
666
sock = None
667
try:
668
sock = await proxy.connect(dest_host, dest_port, timeout=30)
669
yield sock
670
finally:
671
if sock:
672
sock.close()
673
674
# Usage with enhanced features
675
async with proxy_connection_v2('socks5://proxy:1080', 'example.com', 80) as sock:
676
# V2 provides enhanced socket configuration
677
reader, writer = await asyncio.open_connection(
678
host=None, port=None, sock=sock
679
)
680
# ... use connection
681
```