afhamxproxies 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- afhamxproxies-1.0.0/LICENSE +21 -0
- afhamxproxies-1.0.0/PKG-INFO +129 -0
- afhamxproxies-1.0.0/README.md +120 -0
- afhamxproxies-1.0.0/pyproject.toml +15 -0
- afhamxproxies-1.0.0/python/afhamxproxies.egg-info/PKG-INFO +129 -0
- afhamxproxies-1.0.0/python/afhamxproxies.egg-info/SOURCES.txt +9 -0
- afhamxproxies-1.0.0/python/afhamxproxies.egg-info/dependency_links.txt +1 -0
- afhamxproxies-1.0.0/python/afhamxproxies.egg-info/top_level.txt +1 -0
- afhamxproxies-1.0.0/python/afhamxproxies.py +482 -0
- afhamxproxies-1.0.0/setup.cfg +4 -0
- afhamxproxies-1.0.0/tests/test_sdk.py +60 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AfhamXProxies
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: afhamxproxies
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python SDK for AfhamXProxies (Residential, Mobile, and Datacenter proxy routing).
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Dynamic: license-file
|
|
9
|
+
|
|
10
|
+
# afhamxproxies
|
|
11
|
+
|
|
12
|
+
Official Python (sync + async) and Node.js SDK for **AfhamXProxies** (`https://afhamxproxies.xyz`).
|
|
13
|
+
|
|
14
|
+
## Repository Structure
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
afhamxproxies/
|
|
18
|
+
python/
|
|
19
|
+
afhamxproxies.py # Sync, AsyncAfhamXProxies, and SessionPool (zero dependencies)
|
|
20
|
+
node/
|
|
21
|
+
afhamxproxies.mjs # Node.js AfhamXProxies and SessionPool (ESM, zero dependencies)
|
|
22
|
+
examples/
|
|
23
|
+
python_quickstart.py
|
|
24
|
+
node_quickstart.mjs
|
|
25
|
+
tests/
|
|
26
|
+
test_sdk.py
|
|
27
|
+
test_sdk.mjs
|
|
28
|
+
pyproject.toml
|
|
29
|
+
package.json
|
|
30
|
+
LICENSE
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
Python:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install afhamxproxies
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or from GitHub / editable local install:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install git+https://github.com/AfhamDev/afhamxproxies-sdk.git
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or copy `python/afhamxproxies.py` / `node/afhamxproxies.mjs` directly into your project (zero external dependencies).
|
|
48
|
+
|
|
49
|
+
## Supported Pools
|
|
50
|
+
|
|
51
|
+
- `resi`: Residential (global + country/state/city targeting)
|
|
52
|
+
- `resiplus`: Residential+ (real 4G/5G worker & premium residential routing)
|
|
53
|
+
- `mobile`: Mobile 4G/5G
|
|
54
|
+
- `dc`: Datacenter
|
|
55
|
+
|
|
56
|
+
## Python Quickstart
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from afhamxproxies import AfhamXProxies, SessionPool
|
|
60
|
+
|
|
61
|
+
# Reads AFHAMXPROXIES_API_KEY from environment if api_key is omitted
|
|
62
|
+
with AfhamXProxies(pool="resi", country="us", state="california", hold="30m") as client:
|
|
63
|
+
print(client.check_ip())
|
|
64
|
+
client.rotate_session()
|
|
65
|
+
print(client.check_ip())
|
|
66
|
+
|
|
67
|
+
# Scoped sticky session with manual rotation
|
|
68
|
+
with client.sticky(country="de") as sticky:
|
|
69
|
+
print(sticky.proxies)
|
|
70
|
+
sticky.rotate_session()
|
|
71
|
+
|
|
72
|
+
# Concurrent sticky SessionPool with automatic failover rotation
|
|
73
|
+
pool = SessionPool(client, size=5, country="us")
|
|
74
|
+
status, body = pool.get("https://api.ipify.org?format=json", retries=3)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Asyncio
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import asyncio
|
|
81
|
+
from afhamxproxies import AsyncAfhamXProxies
|
|
82
|
+
|
|
83
|
+
async def main():
|
|
84
|
+
async with AsyncAfhamXProxies(pool="mobile", country="in") as client:
|
|
85
|
+
print(await client.check_ip())
|
|
86
|
+
|
|
87
|
+
asyncio.run(main())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Requests / Playwright / Live Pool Discovery
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import requests
|
|
94
|
+
from afhamxproxies import AfhamXProxies
|
|
95
|
+
|
|
96
|
+
client = AfhamXProxies(api_key="YOUR_API_KEY", pool="dc", country="us")
|
|
97
|
+
|
|
98
|
+
# Live Datacenter country availability
|
|
99
|
+
print(client.available_pools()["dc"])
|
|
100
|
+
|
|
101
|
+
# Use with requests
|
|
102
|
+
r = requests.get("https://ipwho.is/", proxies=client.requests_proxies(), timeout=15)
|
|
103
|
+
print(r.json())
|
|
104
|
+
|
|
105
|
+
# Use with Playwright: browser = p.chromium.launch(proxy=client.playwright_proxy(country="gb", city="london"))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Node.js Quickstart
|
|
109
|
+
|
|
110
|
+
```javascript
|
|
111
|
+
import { AfhamXProxies, SessionPool } from "afhamxproxies";
|
|
112
|
+
|
|
113
|
+
const client = new AfhamXProxies({
|
|
114
|
+
apiKey: process.env.AFHAMXPROXIES_API_KEY,
|
|
115
|
+
pool: "resi",
|
|
116
|
+
country: "gb",
|
|
117
|
+
city: "london",
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
console.log(client.proxyUrl());
|
|
121
|
+
console.log(client.axiosConfig());
|
|
122
|
+
console.log(client.playwrightProxy());
|
|
123
|
+
console.log(client.puppeteerArgs());
|
|
124
|
+
console.log(client.generateList({ count: 5, sticky: true }));
|
|
125
|
+
console.log(await client.availablePools());
|
|
126
|
+
|
|
127
|
+
const pool = new SessionPool(client, 5, { country: "us" });
|
|
128
|
+
const { idx, client: slot } = pool.nextSlot();
|
|
129
|
+
```
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# afhamxproxies
|
|
2
|
+
|
|
3
|
+
Official Python (sync + async) and Node.js SDK for **AfhamXProxies** (`https://afhamxproxies.xyz`).
|
|
4
|
+
|
|
5
|
+
## Repository Structure
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
afhamxproxies/
|
|
9
|
+
python/
|
|
10
|
+
afhamxproxies.py # Sync, AsyncAfhamXProxies, and SessionPool (zero dependencies)
|
|
11
|
+
node/
|
|
12
|
+
afhamxproxies.mjs # Node.js AfhamXProxies and SessionPool (ESM, zero dependencies)
|
|
13
|
+
examples/
|
|
14
|
+
python_quickstart.py
|
|
15
|
+
node_quickstart.mjs
|
|
16
|
+
tests/
|
|
17
|
+
test_sdk.py
|
|
18
|
+
test_sdk.mjs
|
|
19
|
+
pyproject.toml
|
|
20
|
+
package.json
|
|
21
|
+
LICENSE
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
Python:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install afhamxproxies
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Or from GitHub / editable local install:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install git+https://github.com/AfhamDev/afhamxproxies-sdk.git
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Or copy `python/afhamxproxies.py` / `node/afhamxproxies.mjs` directly into your project (zero external dependencies).
|
|
39
|
+
|
|
40
|
+
## Supported Pools
|
|
41
|
+
|
|
42
|
+
- `resi`: Residential (global + country/state/city targeting)
|
|
43
|
+
- `resiplus`: Residential+ (real 4G/5G worker & premium residential routing)
|
|
44
|
+
- `mobile`: Mobile 4G/5G
|
|
45
|
+
- `dc`: Datacenter
|
|
46
|
+
|
|
47
|
+
## Python Quickstart
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from afhamxproxies import AfhamXProxies, SessionPool
|
|
51
|
+
|
|
52
|
+
# Reads AFHAMXPROXIES_API_KEY from environment if api_key is omitted
|
|
53
|
+
with AfhamXProxies(pool="resi", country="us", state="california", hold="30m") as client:
|
|
54
|
+
print(client.check_ip())
|
|
55
|
+
client.rotate_session()
|
|
56
|
+
print(client.check_ip())
|
|
57
|
+
|
|
58
|
+
# Scoped sticky session with manual rotation
|
|
59
|
+
with client.sticky(country="de") as sticky:
|
|
60
|
+
print(sticky.proxies)
|
|
61
|
+
sticky.rotate_session()
|
|
62
|
+
|
|
63
|
+
# Concurrent sticky SessionPool with automatic failover rotation
|
|
64
|
+
pool = SessionPool(client, size=5, country="us")
|
|
65
|
+
status, body = pool.get("https://api.ipify.org?format=json", retries=3)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Asyncio
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import asyncio
|
|
72
|
+
from afhamxproxies import AsyncAfhamXProxies
|
|
73
|
+
|
|
74
|
+
async def main():
|
|
75
|
+
async with AsyncAfhamXProxies(pool="mobile", country="in") as client:
|
|
76
|
+
print(await client.check_ip())
|
|
77
|
+
|
|
78
|
+
asyncio.run(main())
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Requests / Playwright / Live Pool Discovery
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import requests
|
|
85
|
+
from afhamxproxies import AfhamXProxies
|
|
86
|
+
|
|
87
|
+
client = AfhamXProxies(api_key="YOUR_API_KEY", pool="dc", country="us")
|
|
88
|
+
|
|
89
|
+
# Live Datacenter country availability
|
|
90
|
+
print(client.available_pools()["dc"])
|
|
91
|
+
|
|
92
|
+
# Use with requests
|
|
93
|
+
r = requests.get("https://ipwho.is/", proxies=client.requests_proxies(), timeout=15)
|
|
94
|
+
print(r.json())
|
|
95
|
+
|
|
96
|
+
# Use with Playwright: browser = p.chromium.launch(proxy=client.playwright_proxy(country="gb", city="london"))
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Node.js Quickstart
|
|
100
|
+
|
|
101
|
+
```javascript
|
|
102
|
+
import { AfhamXProxies, SessionPool } from "afhamxproxies";
|
|
103
|
+
|
|
104
|
+
const client = new AfhamXProxies({
|
|
105
|
+
apiKey: process.env.AFHAMXPROXIES_API_KEY,
|
|
106
|
+
pool: "resi",
|
|
107
|
+
country: "gb",
|
|
108
|
+
city: "london",
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
console.log(client.proxyUrl());
|
|
112
|
+
console.log(client.axiosConfig());
|
|
113
|
+
console.log(client.playwrightProxy());
|
|
114
|
+
console.log(client.puppeteerArgs());
|
|
115
|
+
console.log(client.generateList({ count: 5, sticky: true }));
|
|
116
|
+
console.log(await client.availablePools());
|
|
117
|
+
|
|
118
|
+
const pool = new SessionPool(client, 5, { country: "us" });
|
|
119
|
+
const { idx, client: slot } = pool.nextSlot();
|
|
120
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "afhamxproxies"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "Official Python SDK for AfhamXProxies (Residential, Mobile, and Datacenter proxy routing)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[tool.setuptools]
|
|
14
|
+
package-dir = {"" = "python"}
|
|
15
|
+
py-modules = ["afhamxproxies"]
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: afhamxproxies
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Official Python SDK for AfhamXProxies (Residential, Mobile, and Datacenter proxy routing).
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Dynamic: license-file
|
|
9
|
+
|
|
10
|
+
# afhamxproxies
|
|
11
|
+
|
|
12
|
+
Official Python (sync + async) and Node.js SDK for **AfhamXProxies** (`https://afhamxproxies.xyz`).
|
|
13
|
+
|
|
14
|
+
## Repository Structure
|
|
15
|
+
|
|
16
|
+
```text
|
|
17
|
+
afhamxproxies/
|
|
18
|
+
python/
|
|
19
|
+
afhamxproxies.py # Sync, AsyncAfhamXProxies, and SessionPool (zero dependencies)
|
|
20
|
+
node/
|
|
21
|
+
afhamxproxies.mjs # Node.js AfhamXProxies and SessionPool (ESM, zero dependencies)
|
|
22
|
+
examples/
|
|
23
|
+
python_quickstart.py
|
|
24
|
+
node_quickstart.mjs
|
|
25
|
+
tests/
|
|
26
|
+
test_sdk.py
|
|
27
|
+
test_sdk.mjs
|
|
28
|
+
pyproject.toml
|
|
29
|
+
package.json
|
|
30
|
+
LICENSE
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
Python:
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install afhamxproxies
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or from GitHub / editable local install:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install git+https://github.com/AfhamDev/afhamxproxies-sdk.git
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or copy `python/afhamxproxies.py` / `node/afhamxproxies.mjs` directly into your project (zero external dependencies).
|
|
48
|
+
|
|
49
|
+
## Supported Pools
|
|
50
|
+
|
|
51
|
+
- `resi`: Residential (global + country/state/city targeting)
|
|
52
|
+
- `resiplus`: Residential+ (real 4G/5G worker & premium residential routing)
|
|
53
|
+
- `mobile`: Mobile 4G/5G
|
|
54
|
+
- `dc`: Datacenter
|
|
55
|
+
|
|
56
|
+
## Python Quickstart
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from afhamxproxies import AfhamXProxies, SessionPool
|
|
60
|
+
|
|
61
|
+
# Reads AFHAMXPROXIES_API_KEY from environment if api_key is omitted
|
|
62
|
+
with AfhamXProxies(pool="resi", country="us", state="california", hold="30m") as client:
|
|
63
|
+
print(client.check_ip())
|
|
64
|
+
client.rotate_session()
|
|
65
|
+
print(client.check_ip())
|
|
66
|
+
|
|
67
|
+
# Scoped sticky session with manual rotation
|
|
68
|
+
with client.sticky(country="de") as sticky:
|
|
69
|
+
print(sticky.proxies)
|
|
70
|
+
sticky.rotate_session()
|
|
71
|
+
|
|
72
|
+
# Concurrent sticky SessionPool with automatic failover rotation
|
|
73
|
+
pool = SessionPool(client, size=5, country="us")
|
|
74
|
+
status, body = pool.get("https://api.ipify.org?format=json", retries=3)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Asyncio
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import asyncio
|
|
81
|
+
from afhamxproxies import AsyncAfhamXProxies
|
|
82
|
+
|
|
83
|
+
async def main():
|
|
84
|
+
async with AsyncAfhamXProxies(pool="mobile", country="in") as client:
|
|
85
|
+
print(await client.check_ip())
|
|
86
|
+
|
|
87
|
+
asyncio.run(main())
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Requests / Playwright / Live Pool Discovery
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import requests
|
|
94
|
+
from afhamxproxies import AfhamXProxies
|
|
95
|
+
|
|
96
|
+
client = AfhamXProxies(api_key="YOUR_API_KEY", pool="dc", country="us")
|
|
97
|
+
|
|
98
|
+
# Live Datacenter country availability
|
|
99
|
+
print(client.available_pools()["dc"])
|
|
100
|
+
|
|
101
|
+
# Use with requests
|
|
102
|
+
r = requests.get("https://ipwho.is/", proxies=client.requests_proxies(), timeout=15)
|
|
103
|
+
print(r.json())
|
|
104
|
+
|
|
105
|
+
# Use with Playwright: browser = p.chromium.launch(proxy=client.playwright_proxy(country="gb", city="london"))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Node.js Quickstart
|
|
109
|
+
|
|
110
|
+
```javascript
|
|
111
|
+
import { AfhamXProxies, SessionPool } from "afhamxproxies";
|
|
112
|
+
|
|
113
|
+
const client = new AfhamXProxies({
|
|
114
|
+
apiKey: process.env.AFHAMXPROXIES_API_KEY,
|
|
115
|
+
pool: "resi",
|
|
116
|
+
country: "gb",
|
|
117
|
+
city: "london",
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
console.log(client.proxyUrl());
|
|
121
|
+
console.log(client.axiosConfig());
|
|
122
|
+
console.log(client.playwrightProxy());
|
|
123
|
+
console.log(client.puppeteerArgs());
|
|
124
|
+
console.log(client.generateList({ count: 5, sticky: true }));
|
|
125
|
+
console.log(await client.availablePools());
|
|
126
|
+
|
|
127
|
+
const pool = new SessionPool(client, 5, { country: "us" });
|
|
128
|
+
const { idx, client: slot } = pool.nextSlot();
|
|
129
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
python/afhamxproxies.py
|
|
5
|
+
python/afhamxproxies.egg-info/PKG-INFO
|
|
6
|
+
python/afhamxproxies.egg-info/SOURCES.txt
|
|
7
|
+
python/afhamxproxies.egg-info/dependency_links.txt
|
|
8
|
+
python/afhamxproxies.egg-info/top_level.txt
|
|
9
|
+
tests/test_sdk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
afhamxproxies
|
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
DEFAULT_HOST = "direct.afhamxproxies.xyz"
|
|
15
|
+
DEFAULT_HTTP_PORT = 14680
|
|
16
|
+
DEFAULT_SOCKS_PORT = 14610
|
|
17
|
+
|
|
18
|
+
COUNTRY_ALIASES = {
|
|
19
|
+
"palestine": "ps",
|
|
20
|
+
"uk": "gb",
|
|
21
|
+
"united kingdom": "gb",
|
|
22
|
+
"united states": "us",
|
|
23
|
+
"usa": "us",
|
|
24
|
+
"india": "in",
|
|
25
|
+
"germany": "de",
|
|
26
|
+
"canada": "ca",
|
|
27
|
+
"france": "fr",
|
|
28
|
+
"netherlands": "nl",
|
|
29
|
+
"uae": "ae",
|
|
30
|
+
"global": "rand",
|
|
31
|
+
"random": "rand",
|
|
32
|
+
"any": "rand",
|
|
33
|
+
"all": "rand",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def normalize_country(country: str) -> str:
|
|
38
|
+
c = (country or "rand").strip().lower()
|
|
39
|
+
return COUNTRY_ALIASES.get(c, c)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def build_username(
|
|
43
|
+
pool: str = "resi",
|
|
44
|
+
country: str = "rand",
|
|
45
|
+
state: str = "",
|
|
46
|
+
city: str = "",
|
|
47
|
+
session_id: str | None = None,
|
|
48
|
+
hold: str = "30m",
|
|
49
|
+
rotate: bool = False,
|
|
50
|
+
) -> str:
|
|
51
|
+
p = (pool or "resi").strip().lower()
|
|
52
|
+
cc = normalize_country(country)
|
|
53
|
+
user = f"customer-{p}" if cc == "rand" and rotate else f"customer-{p}-country-{cc}"
|
|
54
|
+
if state.strip():
|
|
55
|
+
user += f"-state-{state.strip().lower().replace(' ', '_')}"
|
|
56
|
+
if city.strip():
|
|
57
|
+
user += f"-city-{city.strip().lower().replace(' ', '')}"
|
|
58
|
+
if rotate:
|
|
59
|
+
return f"{user}-rotate"
|
|
60
|
+
sid = (session_id or secrets.token_hex(4)).replace("-", "").replace("_", "")[:16]
|
|
61
|
+
return f"{user}-sessid_{sid}-hold{hold}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_proxy_url(
|
|
65
|
+
api_key: str,
|
|
66
|
+
pool: str = "resi",
|
|
67
|
+
country: str = "rand",
|
|
68
|
+
state: str = "",
|
|
69
|
+
city: str = "",
|
|
70
|
+
session_id: str | None = None,
|
|
71
|
+
hold: str = "30m",
|
|
72
|
+
rotate: bool = False,
|
|
73
|
+
host: str = DEFAULT_HOST,
|
|
74
|
+
port: int | None = None,
|
|
75
|
+
scheme: str = "http",
|
|
76
|
+
) -> str:
|
|
77
|
+
s = (scheme or "http").strip().lower()
|
|
78
|
+
resolved_port = port if port is not None else (DEFAULT_SOCKS_PORT if s.startswith("socks") else DEFAULT_HTTP_PORT)
|
|
79
|
+
user = build_username(pool=pool, country=country, state=state, city=city, session_id=session_id, hold=hold, rotate=rotate)
|
|
80
|
+
return f"{s}://{user}:{api_key}@{host}:{resolved_port}"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def build_playwright_proxy(
|
|
84
|
+
api_key: str,
|
|
85
|
+
pool: str = "resi",
|
|
86
|
+
country: str = "rand",
|
|
87
|
+
state: str = "",
|
|
88
|
+
city: str = "",
|
|
89
|
+
session_id: str | None = None,
|
|
90
|
+
hold: str = "30m",
|
|
91
|
+
rotate: bool = False,
|
|
92
|
+
host: str = DEFAULT_HOST,
|
|
93
|
+
port: int = DEFAULT_HTTP_PORT,
|
|
94
|
+
scheme: str = "http",
|
|
95
|
+
) -> dict[str, str]:
|
|
96
|
+
return {
|
|
97
|
+
"server": f"{scheme}://{host}:{port}",
|
|
98
|
+
"username": build_username(pool=pool, country=country, state=state, city=city, session_id=session_id, hold=hold, rotate=rotate),
|
|
99
|
+
"password": api_key,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def parse_proxy_url(proxy_url: str) -> dict[str, Any]:
|
|
104
|
+
parsed = urllib.parse.urlparse(proxy_url)
|
|
105
|
+
return {
|
|
106
|
+
"scheme": parsed.scheme or "http",
|
|
107
|
+
"host": parsed.hostname or "",
|
|
108
|
+
"port": parsed.port or (DEFAULT_SOCKS_PORT if (parsed.scheme or "").startswith("socks") else DEFAULT_HTTP_PORT),
|
|
109
|
+
"username": parsed.username or "",
|
|
110
|
+
"password": parsed.password or "",
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def fetch_json(url: str, proxy_url: str, timeout: float = 15.0, retries: int = 2) -> Any:
|
|
115
|
+
opener = urllib.request.build_opener(
|
|
116
|
+
urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url})
|
|
117
|
+
)
|
|
118
|
+
last_err: Exception | None = None
|
|
119
|
+
for attempt in range(retries + 1):
|
|
120
|
+
try:
|
|
121
|
+
req = urllib.request.Request(url, headers={"User-Agent": "curl/8.5.0"})
|
|
122
|
+
with opener.open(req, timeout=timeout) as resp:
|
|
123
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
124
|
+
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
|
|
125
|
+
last_err = exc
|
|
126
|
+
if attempt < retries:
|
|
127
|
+
time.sleep(0.4 * (attempt + 1))
|
|
128
|
+
raise RuntimeError(f"Request failed after {retries + 1} attempts: {last_err}")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class AfhamXProxies:
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
api_key: str | None = None,
|
|
135
|
+
pool: str = "resi",
|
|
136
|
+
country: str = "rand",
|
|
137
|
+
state: str = "",
|
|
138
|
+
city: str = "",
|
|
139
|
+
session_id: str | None = None,
|
|
140
|
+
hold: str = "30m",
|
|
141
|
+
rotate: bool = False,
|
|
142
|
+
host: str = DEFAULT_HOST,
|
|
143
|
+
port: int | None = None,
|
|
144
|
+
scheme: str = "http",
|
|
145
|
+
timeout: float = 15.0,
|
|
146
|
+
retries: int = 2,
|
|
147
|
+
rotate_on_error: bool = True,
|
|
148
|
+
default_headers: dict[str, str] | None = None,
|
|
149
|
+
) -> None:
|
|
150
|
+
key = (api_key or os.environ.get("AFHAMXPROXIES_API_KEY") or os.environ.get("AFHAMX_API_KEY", "")).strip()
|
|
151
|
+
if not key:
|
|
152
|
+
raise ValueError("api_key is required (pass api_key or set AFHAMXPROXIES_API_KEY)")
|
|
153
|
+
self.api_key = key
|
|
154
|
+
self.pool = (pool or "resi").strip().lower()
|
|
155
|
+
self.country = normalize_country(country)
|
|
156
|
+
self.state = state
|
|
157
|
+
self.city = city
|
|
158
|
+
self.session_id = session_id or secrets.token_hex(4)
|
|
159
|
+
self.hold = hold
|
|
160
|
+
self.rotate = rotate
|
|
161
|
+
self.host = host
|
|
162
|
+
self.scheme = (scheme or "http").strip().lower()
|
|
163
|
+
self.port = port if port is not None else (DEFAULT_SOCKS_PORT if self.scheme.startswith("socks") else DEFAULT_HTTP_PORT)
|
|
164
|
+
self.timeout = timeout
|
|
165
|
+
self.retries = retries
|
|
166
|
+
self.rotate_on_error = rotate_on_error
|
|
167
|
+
self.default_headers = dict(default_headers or {"User-Agent": "curl/8.5.0"})
|
|
168
|
+
|
|
169
|
+
def __enter__(self) -> "AfhamXProxies":
|
|
170
|
+
return self
|
|
171
|
+
|
|
172
|
+
def __exit__(self, *_: Any) -> None:
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
def set_geo(self, country: str = "rand", state: str = "", city: str = "") -> "AfhamXProxies":
|
|
176
|
+
self.country = normalize_country(country)
|
|
177
|
+
self.state = state
|
|
178
|
+
self.city = city
|
|
179
|
+
return self
|
|
180
|
+
|
|
181
|
+
def sticky_session(self, session_id: str | None = None, hold: str = "30m") -> "AfhamXProxies":
|
|
182
|
+
self.rotate = False
|
|
183
|
+
self.hold = hold
|
|
184
|
+
self.session_id = session_id or secrets.token_hex(4)
|
|
185
|
+
return self
|
|
186
|
+
|
|
187
|
+
def rotate_session(self) -> str:
|
|
188
|
+
self.session_id = secrets.token_hex(4)
|
|
189
|
+
return self.session_id
|
|
190
|
+
|
|
191
|
+
def username(self, **overrides: Any) -> str:
|
|
192
|
+
return build_username(
|
|
193
|
+
pool=overrides.get("pool", self.pool),
|
|
194
|
+
country=overrides.get("country", self.country),
|
|
195
|
+
state=overrides.get("state", self.state),
|
|
196
|
+
city=overrides.get("city", self.city),
|
|
197
|
+
session_id=overrides.get("session_id", self.session_id),
|
|
198
|
+
hold=overrides.get("hold", self.hold),
|
|
199
|
+
rotate=overrides.get("rotate", self.rotate),
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
def proxy_url(self, scheme: str | None = None, **overrides: Any) -> str:
|
|
203
|
+
s = (scheme or self.scheme).strip().lower()
|
|
204
|
+
p = overrides.get("port", self.port if scheme is None else (DEFAULT_SOCKS_PORT if s.startswith("socks") else DEFAULT_HTTP_PORT))
|
|
205
|
+
return f"{s}://{self.username(**overrides)}:{self.api_key}@{self.host}:{p}"
|
|
206
|
+
|
|
207
|
+
def socks5_url(self, **overrides: Any) -> str:
|
|
208
|
+
return self.proxy_url(scheme="socks5", port=overrides.get("port", DEFAULT_SOCKS_PORT), **overrides)
|
|
209
|
+
|
|
210
|
+
def requests_proxies(self, **overrides: Any) -> dict[str, str]:
|
|
211
|
+
u = self.proxy_url(**overrides)
|
|
212
|
+
return {"http": u, "https": u}
|
|
213
|
+
|
|
214
|
+
def httpx_proxy(self, **overrides: Any) -> str:
|
|
215
|
+
return self.proxy_url(**overrides)
|
|
216
|
+
|
|
217
|
+
def aiohttp_proxy(self, **overrides: Any) -> tuple[str, Any]:
|
|
218
|
+
return f"http://{self.host}:{self.port}", (self.username(**overrides), self.api_key)
|
|
219
|
+
|
|
220
|
+
def playwright_proxy(self, **overrides: Any) -> dict[str, str]:
|
|
221
|
+
return {
|
|
222
|
+
"server": f"{self.scheme}://{self.host}:{self.port}",
|
|
223
|
+
"username": self.username(**overrides),
|
|
224
|
+
"password": self.api_key,
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
def selenium_proxy(self, **overrides: Any) -> str:
|
|
228
|
+
return self.proxy_url(**overrides)
|
|
229
|
+
|
|
230
|
+
@property
|
|
231
|
+
def proxies(self) -> dict[str, str]:
|
|
232
|
+
return self.requests_proxies()
|
|
233
|
+
|
|
234
|
+
def curl_command(self, url: str = "https://ipwho.is/", **overrides: Any) -> str:
|
|
235
|
+
return f'curl -x "{self.proxy_url(**overrides)}" "{url}"'
|
|
236
|
+
|
|
237
|
+
def sticky(
|
|
238
|
+
self,
|
|
239
|
+
country: str | None = None,
|
|
240
|
+
state: str | None = None,
|
|
241
|
+
city: str | None = None,
|
|
242
|
+
hold: str | None = None,
|
|
243
|
+
session_id: str | None = None,
|
|
244
|
+
) -> "AfhamXProxies":
|
|
245
|
+
return AfhamXProxies(
|
|
246
|
+
api_key=self.api_key,
|
|
247
|
+
pool=self.pool,
|
|
248
|
+
country=country if country is not None else self.country,
|
|
249
|
+
state=state if state is not None else self.state,
|
|
250
|
+
city=city if city is not None else self.city,
|
|
251
|
+
session_id=session_id or secrets.token_hex(4),
|
|
252
|
+
hold=hold or self.hold,
|
|
253
|
+
rotate=False,
|
|
254
|
+
host=self.host,
|
|
255
|
+
port=self.port,
|
|
256
|
+
scheme=self.scheme,
|
|
257
|
+
timeout=self.timeout,
|
|
258
|
+
retries=self.retries,
|
|
259
|
+
rotate_on_error=self.rotate_on_error,
|
|
260
|
+
default_headers=self.default_headers,
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
def generate_list(
|
|
264
|
+
self,
|
|
265
|
+
count: int = 10,
|
|
266
|
+
fmt: str = "http://user:pass@host:port",
|
|
267
|
+
sticky: bool = False,
|
|
268
|
+
**overrides: Any,
|
|
269
|
+
) -> list[str]:
|
|
270
|
+
out: list[str] = []
|
|
271
|
+
n = max(1, min(100000, int(count)))
|
|
272
|
+
for _ in range(n):
|
|
273
|
+
sid = secrets.token_hex(4) if sticky else None
|
|
274
|
+
user = self.username(session_id=sid, rotate=not sticky, **overrides)
|
|
275
|
+
s = (overrides.get("scheme", self.scheme) or "http").lower()
|
|
276
|
+
p = overrides.get("port", self.port)
|
|
277
|
+
if fmt == "host:port:user:pass":
|
|
278
|
+
out.append(f"{self.host}:{p}:{user}:{self.api_key}")
|
|
279
|
+
elif fmt == "user:pass@host:port":
|
|
280
|
+
out.append(f"{user}:{self.api_key}@{self.host}:{p}")
|
|
281
|
+
else:
|
|
282
|
+
out.append(f"{s}://{user}:{self.api_key}@{self.host}:{p}")
|
|
283
|
+
return out
|
|
284
|
+
|
|
285
|
+
def save_txt(self, filepath: str, count: int = 10, fmt: str = "http://user:pass@host:port", sticky: bool = False, **overrides: Any) -> str:
|
|
286
|
+
lines = self.generate_list(count=count, fmt=fmt, sticky=sticky, **overrides)
|
|
287
|
+
with open(filepath, "w", encoding="utf-8") as f:
|
|
288
|
+
f.write("\n".join(lines) + "\n")
|
|
289
|
+
return filepath
|
|
290
|
+
|
|
291
|
+
def available_pools(self, pool_port: int = 14700) -> dict[str, Any]:
|
|
292
|
+
req = urllib.request.Request(f"http://{self.host}:{pool_port}/__afx/pools", headers={"User-Agent": "afhamx-sdk/2.0"})
|
|
293
|
+
with urllib.request.urlopen(req, timeout=5.0) as resp:
|
|
294
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
295
|
+
|
|
296
|
+
def request(
|
|
297
|
+
self,
|
|
298
|
+
method: str,
|
|
299
|
+
url: str,
|
|
300
|
+
data: bytes | str | dict[str, Any] | None = None,
|
|
301
|
+
headers: dict[str, str] | None = None,
|
|
302
|
+
**overrides: Any,
|
|
303
|
+
) -> tuple[int, dict[str, str], bytes]:
|
|
304
|
+
hdrs = {**self.default_headers, **(headers or {})}
|
|
305
|
+
payload: bytes | None = None
|
|
306
|
+
if isinstance(data, dict):
|
|
307
|
+
payload = json.dumps(data).encode("utf-8")
|
|
308
|
+
hdrs.setdefault("Content-Type", "application/json")
|
|
309
|
+
elif isinstance(data, str):
|
|
310
|
+
payload = data.encode("utf-8")
|
|
311
|
+
elif isinstance(data, bytes):
|
|
312
|
+
payload = data
|
|
313
|
+
|
|
314
|
+
last_err: Exception | None = None
|
|
315
|
+
for attempt in range(self.retries + 1):
|
|
316
|
+
if attempt > 0 and self.rotate_on_error and not self.rotate:
|
|
317
|
+
self.rotate_session()
|
|
318
|
+
proxy_url = self.proxy_url(**overrides)
|
|
319
|
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url}))
|
|
320
|
+
try:
|
|
321
|
+
req = urllib.request.Request(url, data=payload, headers=hdrs, method=method.upper())
|
|
322
|
+
with opener.open(req, timeout=self.timeout) as resp:
|
|
323
|
+
return resp.status, dict(resp.headers.items()), resp.read()
|
|
324
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
325
|
+
last_err = exc
|
|
326
|
+
if attempt < self.retries:
|
|
327
|
+
time.sleep(0.35 * (attempt + 1))
|
|
328
|
+
raise RuntimeError(f"{method.upper()} {url} failed after {self.retries + 1} attempts: {last_err}")
|
|
329
|
+
|
|
330
|
+
def get(self, url: str, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, bytes]:
|
|
331
|
+
status, _, body = self.request("GET", url, headers=headers, **overrides)
|
|
332
|
+
return status, body
|
|
333
|
+
|
|
334
|
+
def post(self, url: str, data: bytes | str | dict[str, Any] | None = None, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, bytes]:
|
|
335
|
+
status, _, body = self.request("POST", url, data=data, headers=headers, **overrides)
|
|
336
|
+
return status, body
|
|
337
|
+
|
|
338
|
+
def put(self, url: str, data: bytes | str | dict[str, Any] | None = None, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, bytes]:
|
|
339
|
+
status, _, body = self.request("PUT", url, data=data, headers=headers, **overrides)
|
|
340
|
+
return status, body
|
|
341
|
+
|
|
342
|
+
def delete(self, url: str, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, bytes]:
|
|
343
|
+
status, _, body = self.request("DELETE", url, headers=headers, **overrides)
|
|
344
|
+
return status, body
|
|
345
|
+
|
|
346
|
+
def head(self, url: str, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, dict[str, str]]:
|
|
347
|
+
status, resp_headers, _ = self.request("HEAD", url, headers=headers, **overrides)
|
|
348
|
+
return status, resp_headers
|
|
349
|
+
|
|
350
|
+
def get_json(self, url: str, headers: dict[str, str] | None = None, **overrides: Any) -> Any:
|
|
351
|
+
_, body = self.get(url, headers=headers, **overrides)
|
|
352
|
+
return json.loads(body.decode("utf-8"))
|
|
353
|
+
|
|
354
|
+
def post_json(self, url: str, payload: dict[str, Any], headers: dict[str, str] | None = None, **overrides: Any) -> Any:
|
|
355
|
+
_, body = self.post(url, data=payload, headers=headers, **overrides)
|
|
356
|
+
return json.loads(body.decode("utf-8"))
|
|
357
|
+
|
|
358
|
+
def check_ip(self, **overrides: Any) -> dict[str, Any]:
|
|
359
|
+
return self.get_json("https://ipwho.is/", **overrides)
|
|
360
|
+
|
|
361
|
+
def speed_test(self, url: str = "https://api.ipify.org?format=json", **overrides: Any) -> dict[str, Any]:
|
|
362
|
+
t0 = time.perf_counter()
|
|
363
|
+
status, body = self.get(url, **overrides)
|
|
364
|
+
elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 2)
|
|
365
|
+
kbps = round((len(body) / 1024.0) / max(elapsed_ms / 1000.0, 0.001), 2)
|
|
366
|
+
return {
|
|
367
|
+
"status": status,
|
|
368
|
+
"bytes": len(body),
|
|
369
|
+
"latency_ms": elapsed_ms,
|
|
370
|
+
"speed_kbps": kbps,
|
|
371
|
+
"body": body.decode("utf-8", "ignore"),
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
class AsyncAfhamXProxies:
|
|
376
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
377
|
+
self._sync = AfhamXProxies(*args, **kwargs)
|
|
378
|
+
|
|
379
|
+
async def __aenter__(self) -> "AsyncAfhamXProxies":
|
|
380
|
+
return self
|
|
381
|
+
|
|
382
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
383
|
+
return None
|
|
384
|
+
|
|
385
|
+
def set_geo(self, country: str = "rand", state: str = "", city: str = "") -> "AsyncAfhamXProxies":
|
|
386
|
+
self._sync.set_geo(country=country, state=state, city=city)
|
|
387
|
+
return self
|
|
388
|
+
|
|
389
|
+
def sticky_session(self, session_id: str | None = None, hold: str = "30m") -> "AsyncAfhamXProxies":
|
|
390
|
+
self._sync.sticky_session(session_id=session_id, hold=hold)
|
|
391
|
+
return self
|
|
392
|
+
|
|
393
|
+
def rotate_session(self) -> str:
|
|
394
|
+
return self._sync.rotate_session()
|
|
395
|
+
|
|
396
|
+
def proxy_url(self, scheme: str | None = None, **overrides: Any) -> str:
|
|
397
|
+
return self._sync.proxy_url(scheme=scheme, **overrides)
|
|
398
|
+
|
|
399
|
+
def socks5_url(self, **overrides: Any) -> str:
|
|
400
|
+
return self._sync.socks5_url(**overrides)
|
|
401
|
+
|
|
402
|
+
def playwright_proxy(self, **overrides: Any) -> dict[str, str]:
|
|
403
|
+
return self._sync.playwright_proxy(**overrides)
|
|
404
|
+
|
|
405
|
+
def generate_list(self, count: int = 10, fmt: str = "http://user:pass@host:port", sticky: bool = False, **overrides: Any) -> list[str]:
|
|
406
|
+
return self._sync.generate_list(count=count, fmt=fmt, sticky=sticky, **overrides)
|
|
407
|
+
|
|
408
|
+
async def request(self, method: str, url: str, data: bytes | str | dict[str, Any] | None = None, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, dict[str, str], bytes]:
|
|
409
|
+
return await asyncio.to_thread(self._sync.request, method, url, data, headers, **overrides)
|
|
410
|
+
|
|
411
|
+
async def get(self, url: str, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, bytes]:
|
|
412
|
+
return await asyncio.to_thread(self._sync.get, url, headers, **overrides)
|
|
413
|
+
|
|
414
|
+
async def post(self, url: str, data: bytes | str | dict[str, Any] | None = None, headers: dict[str, str] | None = None, **overrides: Any) -> tuple[int, bytes]:
|
|
415
|
+
return await asyncio.to_thread(self._sync.post, url, data, headers, **overrides)
|
|
416
|
+
|
|
417
|
+
async def get_json(self, url: str, headers: dict[str, str] | None = None, **overrides: Any) -> Any:
|
|
418
|
+
return await asyncio.to_thread(self._sync.get_json, url, headers, **overrides)
|
|
419
|
+
|
|
420
|
+
async def post_json(self, url: str, payload: dict[str, Any], headers: dict[str, str] | None = None, **overrides: Any) -> Any:
|
|
421
|
+
return await asyncio.to_thread(self._sync.post_json, url, payload, headers, **overrides)
|
|
422
|
+
|
|
423
|
+
async def check_ip(self, **overrides: Any) -> dict[str, Any]:
|
|
424
|
+
return await asyncio.to_thread(self._sync.check_ip, **overrides)
|
|
425
|
+
|
|
426
|
+
async def speed_test(self, url: str = "https://api.ipify.org?format=json", **overrides: Any) -> dict[str, Any]:
|
|
427
|
+
return await asyncio.to_thread(self._sync.speed_test, url, **overrides)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
class SessionPool:
|
|
431
|
+
"""Manages N concurrent sticky AfhamXProxies slots with automatic slot rotation on failure/blocks."""
|
|
432
|
+
|
|
433
|
+
def __init__(self, client_or_key: AfhamXProxies | str, size: int = 5, **kwargs: Any) -> None:
|
|
434
|
+
base = client_or_key if isinstance(client_or_key, AfhamXProxies) else AfhamXProxies(api_key=client_or_key, **kwargs)
|
|
435
|
+
self.slots: list[AfhamXProxies] = [
|
|
436
|
+
base.sticky(
|
|
437
|
+
country=kwargs.get("country", base.country),
|
|
438
|
+
state=kwargs.get("state", base.state),
|
|
439
|
+
city=kwargs.get("city", base.city),
|
|
440
|
+
hold=kwargs.get("hold", base.hold),
|
|
441
|
+
)
|
|
442
|
+
for _ in range(max(1, int(size)))
|
|
443
|
+
]
|
|
444
|
+
self._idx = 0
|
|
445
|
+
|
|
446
|
+
def next_slot(self) -> tuple[int, AfhamXProxies]:
|
|
447
|
+
idx = self._idx % len(self.slots)
|
|
448
|
+
self._idx += 1
|
|
449
|
+
return idx, self.slots[idx]
|
|
450
|
+
|
|
451
|
+
def rotate_slot(self, idx: int) -> str:
|
|
452
|
+
return self.slots[idx % len(self.slots)].rotate_session()
|
|
453
|
+
|
|
454
|
+
def request(
|
|
455
|
+
self,
|
|
456
|
+
method: str,
|
|
457
|
+
url: str,
|
|
458
|
+
retries: int = 3,
|
|
459
|
+
data: bytes | str | dict[str, Any] | None = None,
|
|
460
|
+
headers: dict[str, str] | None = None,
|
|
461
|
+
) -> tuple[int, dict[str, str], bytes]:
|
|
462
|
+
last_err: Exception | None = None
|
|
463
|
+
for _ in range(max(1, retries)):
|
|
464
|
+
idx, slot = self.next_slot()
|
|
465
|
+
try:
|
|
466
|
+
status, resp_headers, body = slot.request(method, url, data=data, headers=headers)
|
|
467
|
+
if status in (403, 429, 502, 503):
|
|
468
|
+
self.rotate_slot(idx)
|
|
469
|
+
continue
|
|
470
|
+
return status, resp_headers, body
|
|
471
|
+
except Exception as exc:
|
|
472
|
+
last_err = exc
|
|
473
|
+
self.rotate_slot(idx)
|
|
474
|
+
raise RuntimeError(f"SessionPool {method.upper()} {url} failed after {retries} retries: {last_err}")
|
|
475
|
+
|
|
476
|
+
def get(self, url: str, retries: int = 3, headers: dict[str, str] | None = None) -> tuple[int, bytes]:
|
|
477
|
+
status, _, body = self.request("GET", url, retries=retries, headers=headers)
|
|
478
|
+
return status, body
|
|
479
|
+
|
|
480
|
+
def post(self, url: str, data: bytes | str | dict[str, Any] | None = None, retries: int = 3, headers: dict[str, str] | None = None) -> tuple[int, bytes]:
|
|
481
|
+
status, _, body = self.request("POST", url, retries=retries, data=data, headers=headers)
|
|
482
|
+
return status, body
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import sys
|
|
3
|
+
import unittest
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "python"))
|
|
7
|
+
import afhamxproxies
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestAfhamXProxiesSDK(unittest.TestCase):
|
|
11
|
+
def test_client_env_and_rotation(self):
|
|
12
|
+
prev = os.environ.get("AFHAMXPROXIES_API_KEY")
|
|
13
|
+
os.environ["AFHAMXPROXIES_API_KEY"] = "test_key_123"
|
|
14
|
+
try:
|
|
15
|
+
with afhamxproxies.AfhamXProxies(pool="resi", country="us", state="new_york", session_id="s1") as c:
|
|
16
|
+
self.assertEqual(
|
|
17
|
+
c.proxy_url(),
|
|
18
|
+
"http://customer-resi-country-us-state-new_york-sessid_s1-hold30m:test_key_123@direct.afhamxproxies.xyz:14680",
|
|
19
|
+
)
|
|
20
|
+
old_sid = c.session_id
|
|
21
|
+
new_sid = c.rotate_session()
|
|
22
|
+
self.assertNotEqual(old_sid, new_sid)
|
|
23
|
+
pw = c.playwright_proxy(country="gb", state="", city="london")
|
|
24
|
+
self.assertIn("customer-resi-country-gb-city-london", pw["username"])
|
|
25
|
+
finally:
|
|
26
|
+
if prev is None:
|
|
27
|
+
os.environ.pop("AFHAMXPROXIES_API_KEY", None)
|
|
28
|
+
else:
|
|
29
|
+
os.environ["AFHAMXPROXIES_API_KEY"] = prev
|
|
30
|
+
|
|
31
|
+
def test_missing_key_raises(self):
|
|
32
|
+
prev = os.environ.pop("AFHAMXPROXIES_API_KEY", None)
|
|
33
|
+
prev_alt = os.environ.pop("AFHAMX_API_KEY", None)
|
|
34
|
+
try:
|
|
35
|
+
with self.assertRaises(ValueError):
|
|
36
|
+
afhamxproxies.AfhamXProxies()
|
|
37
|
+
finally:
|
|
38
|
+
if prev is not None:
|
|
39
|
+
os.environ["AFHAMXPROXIES_API_KEY"] = prev
|
|
40
|
+
if prev_alt is not None:
|
|
41
|
+
os.environ["AFHAMX_API_KEY"] = prev_alt
|
|
42
|
+
|
|
43
|
+
def test_sticky_and_session_pool(self):
|
|
44
|
+
client = afhamxproxies.AfhamXProxies(api_key="test_key_123", pool="mobile", country="pk")
|
|
45
|
+
with client.sticky(country="tr", hold="15m") as s:
|
|
46
|
+
self.assertIn("customer-mobile-country-tr-sessid_", s.username())
|
|
47
|
+
self.assertIn("-hold15m", s.username())
|
|
48
|
+
self.assertIn("http", s.proxies)
|
|
49
|
+
old_sid = s.session_id
|
|
50
|
+
new_sid = s.rotate_session()
|
|
51
|
+
self.assertNotEqual(old_sid, new_sid)
|
|
52
|
+
pool = afhamxproxies.SessionPool(client, size=3, country="de")
|
|
53
|
+
self.assertEqual(len(pool.slots), 3)
|
|
54
|
+
idx, slot = pool.next_slot()
|
|
55
|
+
self.assertEqual(idx, 0)
|
|
56
|
+
self.assertIn("customer-mobile-country-de-sessid_", slot.username())
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
unittest.main()
|