fastapi-ip2proxy 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.
- fastapi_ip2proxy-1.0.0/LICENSE.TXT +21 -0
- fastapi_ip2proxy-1.0.0/PKG-INFO +146 -0
- fastapi_ip2proxy-1.0.0/README.md +114 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy/__init__.py +3 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy/middleware.py +219 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy.egg-info/PKG-INFO +146 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy.egg-info/SOURCES.txt +11 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy.egg-info/dependency_links.txt +1 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy.egg-info/requires.txt +8 -0
- fastapi_ip2proxy-1.0.0/fastapi_ip2proxy.egg-info/top_level.txt +1 -0
- fastapi_ip2proxy-1.0.0/pyproject.toml +49 -0
- fastapi_ip2proxy-1.0.0/setup.cfg +4 -0
- fastapi_ip2proxy-1.0.0/tests/test_middleware.py +93 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 - 2026 IP2Location.com
|
|
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,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-ip2proxy
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A FastAPI middleware SDK for the IP2Proxy Python library.
|
|
5
|
+
Author-email: IP2Location <support@ip2location.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ip2location/fastapi-ip2proxy
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/ip2location/fastapi-ip2proxy/issues
|
|
9
|
+
Keywords: fastapi,ip2proxy,proxy,middleware,ip
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Framework :: FastAPI
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
|
|
21
|
+
Requires-Python: >=3.8
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE.TXT
|
|
24
|
+
Requires-Dist: fastapi>=0.68.0
|
|
25
|
+
Requires-Dist: starlette>=0.14.0
|
|
26
|
+
Requires-Dist: IP2Proxy>=3.6.1
|
|
27
|
+
Requires-Dist: httpx>=0.24.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
30
|
+
Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# FastAPI IP2Location Middleware
|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
A high-performance, asynchronous FastAPI middleware that automatically geolocates incoming requests using the [IP2Location](https://www.ip2location.com/database/proxy) database or the [IP2Location.io](https://www.ip2location.io/) API. It seamlessly injects the geolocation data directly into the `request.state.location` object for easy access in your route handlers.
|
|
37
|
+
|
|
38
|
+
## Features
|
|
39
|
+
|
|
40
|
+
- **Dual Mode Support**: Use a local `.BIN` database for ultra-fast, zero-latency lookups, or use the IP2Location.io API if you don't want to host the database.
|
|
41
|
+
- **Async & Connection Pooling**: Built with `httpx` for non-blocking API calls, utilizing connection pooling to ensure high throughput.
|
|
42
|
+
- **Proxy Aware**: Automatically extracts the real client IP from headers like `X-Forwarded-For` or `X-Real-IP` when deployed behind load balancers or reverse proxies (like Nginx, Cloudflare, or AWS ALB).
|
|
43
|
+
- **Local Development Friendly**: Includes a `test_ip` parameter to easily override `127.0.0.1` and test specific geographic locations locally.
|
|
44
|
+
- **Multilingual Support**: Supports the `language` parameter (API mode) to return localized names for countries, regions, and cities.
|
|
45
|
+
- **Graceful Degradation**: Never crashes your app. If a lookup fails, it safely injects an error message into the state object so your app can decide how to handle it.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
Install the package via pip:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install fastapi-ip2proxy
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Prerequisites
|
|
56
|
+
|
|
57
|
+
You need at least one of the following to use this middleware:
|
|
58
|
+
|
|
59
|
+
- Local Database (.BIN): Download a free IP2Proxy Lite database (e.g., PX12) from [IP2Location Lite](https://www.ip2location.com/database/lite).
|
|
60
|
+
|
|
61
|
+
- API Key: Sign up for an API key at IP2Location.io.
|
|
62
|
+
|
|
63
|
+
## Usage Examples
|
|
64
|
+
|
|
65
|
+
1. Using the Local Database (Recommended for Production)
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from fastapi import FastAPI, Request
|
|
69
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
70
|
+
|
|
71
|
+
app = FastAPI()
|
|
72
|
+
|
|
73
|
+
app.add_middleware(
|
|
74
|
+
IP2ProxyMiddleware,
|
|
75
|
+
bin_path="IP2PROXY-LITE-PX12.BIN", # Path to your downloaded .BIN file
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@app.get("/")
|
|
79
|
+
async def get_location(request: Request):
|
|
80
|
+
return {"your_location": request.state.proxy}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
2. Using the IP2Location.io API
|
|
84
|
+
```python
|
|
85
|
+
import os
|
|
86
|
+
from fastapi import FastAPI, Request
|
|
87
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
88
|
+
|
|
89
|
+
app = FastAPI()
|
|
90
|
+
|
|
91
|
+
app.add_middleware(
|
|
92
|
+
IP2ProxyMiddleware,
|
|
93
|
+
api_key=os.getenv("IP2LOCATION_API_KEY")
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
@app.get("/")
|
|
97
|
+
async def get_location(request: Request):
|
|
98
|
+
return {"your_location": request.state.proxy}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Advanced Configuration
|
|
102
|
+
|
|
103
|
+
You can fully customize the middleware to suit your environment:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
app.add_middleware(
|
|
107
|
+
IP2ProxyMiddleware,
|
|
108
|
+
bin_path="IP2PROXY-LITE-PX12.BIN",
|
|
109
|
+
api_key="OPTIONAL_FALLBACK_KEY",
|
|
110
|
+
|
|
111
|
+
# Checks these headers first for the real IP.
|
|
112
|
+
# Defaults to ["X-Forwarded-For", "X-Real-IP"]
|
|
113
|
+
ip_headers=["X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP"],
|
|
114
|
+
|
|
115
|
+
# If the user connects from localhost (127.0.0.1), pretend they are
|
|
116
|
+
# connecting from this IP instead. Great for local testing!
|
|
117
|
+
test_ip="8.8.8.8",
|
|
118
|
+
|
|
119
|
+
# Translate country/city names (Requires API mode and a supported plan)
|
|
120
|
+
language="fr"
|
|
121
|
+
)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Accessing the Data
|
|
125
|
+
|
|
126
|
+
The middleware standardizes the output regardless of whether you use the .BIN file or the API. The dictionary injected into request.state.proxy includes the following keys:
|
|
127
|
+
|
|
128
|
+
```json
|
|
129
|
+
{
|
|
130
|
+
"ip": "8.8.8.8",
|
|
131
|
+
"country_short": "US",
|
|
132
|
+
"country_long": "United States",
|
|
133
|
+
"region": "California",
|
|
134
|
+
"city": "Mountain View",
|
|
135
|
+
"asn": "15169",
|
|
136
|
+
"as": "Google LLC",
|
|
137
|
+
"is_proxy": false,
|
|
138
|
+
"error": null
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
*(Note: Premium data fields like proxy data will also be populated if your specific .BIN file or API plan supports them).*
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
This project is licensed under the MIT License.
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# FastAPI IP2Location Middleware
|
|
2
|
+

|
|
3
|
+
|
|
4
|
+
A high-performance, asynchronous FastAPI middleware that automatically geolocates incoming requests using the [IP2Location](https://www.ip2location.com/database/proxy) database or the [IP2Location.io](https://www.ip2location.io/) API. It seamlessly injects the geolocation data directly into the `request.state.location` object for easy access in your route handlers.
|
|
5
|
+
|
|
6
|
+
## Features
|
|
7
|
+
|
|
8
|
+
- **Dual Mode Support**: Use a local `.BIN` database for ultra-fast, zero-latency lookups, or use the IP2Location.io API if you don't want to host the database.
|
|
9
|
+
- **Async & Connection Pooling**: Built with `httpx` for non-blocking API calls, utilizing connection pooling to ensure high throughput.
|
|
10
|
+
- **Proxy Aware**: Automatically extracts the real client IP from headers like `X-Forwarded-For` or `X-Real-IP` when deployed behind load balancers or reverse proxies (like Nginx, Cloudflare, or AWS ALB).
|
|
11
|
+
- **Local Development Friendly**: Includes a `test_ip` parameter to easily override `127.0.0.1` and test specific geographic locations locally.
|
|
12
|
+
- **Multilingual Support**: Supports the `language` parameter (API mode) to return localized names for countries, regions, and cities.
|
|
13
|
+
- **Graceful Degradation**: Never crashes your app. If a lookup fails, it safely injects an error message into the state object so your app can decide how to handle it.
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
Install the package via pip:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install fastapi-ip2proxy
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Prerequisites
|
|
24
|
+
|
|
25
|
+
You need at least one of the following to use this middleware:
|
|
26
|
+
|
|
27
|
+
- Local Database (.BIN): Download a free IP2Proxy Lite database (e.g., PX12) from [IP2Location Lite](https://www.ip2location.com/database/lite).
|
|
28
|
+
|
|
29
|
+
- API Key: Sign up for an API key at IP2Location.io.
|
|
30
|
+
|
|
31
|
+
## Usage Examples
|
|
32
|
+
|
|
33
|
+
1. Using the Local Database (Recommended for Production)
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from fastapi import FastAPI, Request
|
|
37
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
38
|
+
|
|
39
|
+
app = FastAPI()
|
|
40
|
+
|
|
41
|
+
app.add_middleware(
|
|
42
|
+
IP2ProxyMiddleware,
|
|
43
|
+
bin_path="IP2PROXY-LITE-PX12.BIN", # Path to your downloaded .BIN file
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
@app.get("/")
|
|
47
|
+
async def get_location(request: Request):
|
|
48
|
+
return {"your_location": request.state.proxy}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
2. Using the IP2Location.io API
|
|
52
|
+
```python
|
|
53
|
+
import os
|
|
54
|
+
from fastapi import FastAPI, Request
|
|
55
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
56
|
+
|
|
57
|
+
app = FastAPI()
|
|
58
|
+
|
|
59
|
+
app.add_middleware(
|
|
60
|
+
IP2ProxyMiddleware,
|
|
61
|
+
api_key=os.getenv("IP2LOCATION_API_KEY")
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
@app.get("/")
|
|
65
|
+
async def get_location(request: Request):
|
|
66
|
+
return {"your_location": request.state.proxy}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Advanced Configuration
|
|
70
|
+
|
|
71
|
+
You can fully customize the middleware to suit your environment:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
app.add_middleware(
|
|
75
|
+
IP2ProxyMiddleware,
|
|
76
|
+
bin_path="IP2PROXY-LITE-PX12.BIN",
|
|
77
|
+
api_key="OPTIONAL_FALLBACK_KEY",
|
|
78
|
+
|
|
79
|
+
# Checks these headers first for the real IP.
|
|
80
|
+
# Defaults to ["X-Forwarded-For", "X-Real-IP"]
|
|
81
|
+
ip_headers=["X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP"],
|
|
82
|
+
|
|
83
|
+
# If the user connects from localhost (127.0.0.1), pretend they are
|
|
84
|
+
# connecting from this IP instead. Great for local testing!
|
|
85
|
+
test_ip="8.8.8.8",
|
|
86
|
+
|
|
87
|
+
# Translate country/city names (Requires API mode and a supported plan)
|
|
88
|
+
language="fr"
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Accessing the Data
|
|
93
|
+
|
|
94
|
+
The middleware standardizes the output regardless of whether you use the .BIN file or the API. The dictionary injected into request.state.proxy includes the following keys:
|
|
95
|
+
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"ip": "8.8.8.8",
|
|
99
|
+
"country_short": "US",
|
|
100
|
+
"country_long": "United States",
|
|
101
|
+
"region": "California",
|
|
102
|
+
"city": "Mountain View",
|
|
103
|
+
"asn": "15169",
|
|
104
|
+
"as": "Google LLC",
|
|
105
|
+
"is_proxy": false,
|
|
106
|
+
"error": null
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
*(Note: Premium data fields like proxy data will also be populated if your specific .BIN file or API plan supports them).*
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
This project is licensed under the MIT License.
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import httpx
|
|
3
|
+
import IP2Proxy
|
|
4
|
+
from fastapi import Request
|
|
5
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
6
|
+
from typing import Optional, List
|
|
7
|
+
|
|
8
|
+
class IP2ProxyMiddleware(BaseHTTPMiddleware):
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
app,
|
|
12
|
+
bin_path: Optional[str] = None,
|
|
13
|
+
api_key: Optional[str] = None,
|
|
14
|
+
use_memory: bool = True,
|
|
15
|
+
ip_headers: Optional[List[str]] = None,
|
|
16
|
+
test_ip: Optional[str] = None,
|
|
17
|
+
language: Optional[str] = None # Added language parameter
|
|
18
|
+
):
|
|
19
|
+
super().__init__(app)
|
|
20
|
+
|
|
21
|
+
# Validation: Must have at least one method of lookup
|
|
22
|
+
if not bin_path and not api_key:
|
|
23
|
+
raise ValueError(
|
|
24
|
+
"Configuration Error: You must provide either 'bin_path' (for local BIN file) "
|
|
25
|
+
"or 'api_key' (for IP2Location.io API)."
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
self.db_path = bin_path
|
|
29
|
+
self.api_key = api_key
|
|
30
|
+
self.ip_headers = ip_headers or ["X-Forwarded-For", "X-Real-IP"]
|
|
31
|
+
self.test_ip = test_ip
|
|
32
|
+
self.language = language
|
|
33
|
+
|
|
34
|
+
self.ip2pro_db = None
|
|
35
|
+
self.http_client = None # Placeholder for our HTTP connection pool
|
|
36
|
+
|
|
37
|
+
# Initialize Local DB if a path is provided
|
|
38
|
+
if self.db_path:
|
|
39
|
+
if not os.path.exists(self.db_path):
|
|
40
|
+
raise FileNotFoundError(f"IP2Proxy database not found at {self.db_path}")
|
|
41
|
+
try:
|
|
42
|
+
# mode = "SHARED_MEMORY" if use_memory else "FILE_IO"
|
|
43
|
+
# self.ip2pro_db = IP2Proxy.IP2Proxy(self.db_path)
|
|
44
|
+
self.ip2pro_db = IP2Proxy.IP2Proxy()
|
|
45
|
+
self.ip2pro_db.open(self.db_path)
|
|
46
|
+
except Exception as e:
|
|
47
|
+
raise RuntimeError(f"Failed to initialize IP2Proxy database: {e}")
|
|
48
|
+
|
|
49
|
+
def _get_client_ip(self, request: Request) -> str:
|
|
50
|
+
"""Extracts the real client IP, respecting proxy headers and test IPs."""
|
|
51
|
+
client_ip = None
|
|
52
|
+
|
|
53
|
+
# 1. Check Headers first
|
|
54
|
+
for header in self.ip_headers:
|
|
55
|
+
if header in request.headers:
|
|
56
|
+
client_ip = request.headers[header].split(",")[0].strip()
|
|
57
|
+
break
|
|
58
|
+
|
|
59
|
+
# 2. Fallback to direct connection IP
|
|
60
|
+
if not client_ip:
|
|
61
|
+
client_ip = request.client.host if request.client else "127.0.0.1"
|
|
62
|
+
|
|
63
|
+
# 3. OVERRIDE: If it's a local IP and a test_ip is provided, use the test_ip
|
|
64
|
+
if self.test_ip and client_ip in ("127.0.0.1", "::1", "localhost"):
|
|
65
|
+
return self.test_ip
|
|
66
|
+
|
|
67
|
+
return client_ip
|
|
68
|
+
|
|
69
|
+
async def dispatch(self, request: Request, call_next):
|
|
70
|
+
client_ip = self._get_client_ip(request)
|
|
71
|
+
|
|
72
|
+
# Base proxy object
|
|
73
|
+
proxy_data = {
|
|
74
|
+
"ip": client_ip,
|
|
75
|
+
"error": None
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
# 1. Prioritize Local DB if both are provided (faster, no network latency)
|
|
80
|
+
if self.ip2pro_db:
|
|
81
|
+
record = self.ip2pro_db.get_all(client_ip)
|
|
82
|
+
proxy_data.update({
|
|
83
|
+
"is_proxy": record['is_proxy'] if 'is_proxy' in record else None,
|
|
84
|
+
"proxy_type": record['proxy_type'] if 'proxy_type' in record else None,
|
|
85
|
+
"country_short": record['country_short'] if 'country_short' in record else None,
|
|
86
|
+
"country_long": record['country_long'] if 'country_long' in record else None,
|
|
87
|
+
"region": record['region'] if 'region' in record else None,
|
|
88
|
+
"city": record['city'] if 'city' in record else None,
|
|
89
|
+
"isp": record['isp'] if 'isp' in record else None,
|
|
90
|
+
"domain": record['domain'] if 'domain' in record else None,
|
|
91
|
+
"usage_type": record['usage_type'] if 'usage_type' in record else None,
|
|
92
|
+
"asn": record['asn'] if 'asn' in record else None,
|
|
93
|
+
"as_name": record['as_name'] if 'as_name' in record else None,
|
|
94
|
+
"last_seen": record['last_seen'] if 'last_seen' in record else None,
|
|
95
|
+
"threat": record['threat'] if 'threat' in record else None,
|
|
96
|
+
"provider": record['provider'] if 'provider' in record else None,
|
|
97
|
+
"fraud_score": record['fraud_score'] if 'fraud_score' in record else None,
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
# 2. Fallback to API if DB is not configured
|
|
101
|
+
elif self.api_key:
|
|
102
|
+
# Initialize the httpx client once per application lifecycle (Connection Pooling)
|
|
103
|
+
if self.http_client is None:
|
|
104
|
+
self.http_client = httpx.AsyncClient()
|
|
105
|
+
|
|
106
|
+
# Construct the API URL
|
|
107
|
+
api_url = f"https://api.ip2location.io/?key={self.api_key}&ip={client_ip}"
|
|
108
|
+
|
|
109
|
+
# Append the language parameter if provided (ignored if free plan drops it)
|
|
110
|
+
if self.language:
|
|
111
|
+
api_url += f"&lang={self.language}"
|
|
112
|
+
|
|
113
|
+
# Make the non-blocking asynchronous request using the pooled client
|
|
114
|
+
response = await self.http_client.get(api_url)
|
|
115
|
+
response.raise_for_status()
|
|
116
|
+
data = response.json()
|
|
117
|
+
|
|
118
|
+
# Map API response keys to match our standard format
|
|
119
|
+
proxy_data.update({
|
|
120
|
+
"country_short": data.get("country_code"),
|
|
121
|
+
"country_long": data.get("country_name"),
|
|
122
|
+
"region": data.get("region_name"),
|
|
123
|
+
"city": data.get("city_name"),
|
|
124
|
+
# "district": data.get("district"),
|
|
125
|
+
# "latitude": data.get("latitude"),
|
|
126
|
+
# "longitude": data.get("longitude"),
|
|
127
|
+
# "zipcode": data.get("zip_code"),
|
|
128
|
+
# "timezone": data.get("time_zone"),
|
|
129
|
+
"asn": data.get("asn"),
|
|
130
|
+
"as": data.get("as"),
|
|
131
|
+
"isp": data.get("isp"),
|
|
132
|
+
"domain": data.get("domain"),
|
|
133
|
+
# "net_speed": data.get("net_speed"),
|
|
134
|
+
# "idd_code": data.get("idd_code"),
|
|
135
|
+
# "area_code": data.get("area_code"),
|
|
136
|
+
# "weather_station_code": data.get("weather_station_code"),
|
|
137
|
+
# "weather_station_name": data.get("weather_station_name"),
|
|
138
|
+
# "mcc": data.get("mcc"),
|
|
139
|
+
# "mnc": data.get("mnc"),
|
|
140
|
+
# "mobile_brand": data.get("mobile_brand"),
|
|
141
|
+
# "elevation": data.get("elevation"),
|
|
142
|
+
"usage_type": data.get("usage_type"),
|
|
143
|
+
# "address_type": data.get("address_type"),
|
|
144
|
+
# "ads_category": data.get("ads_category"),
|
|
145
|
+
# "ads_category_name": data.get("ads_category_name"),
|
|
146
|
+
# AS info data
|
|
147
|
+
# "as_name": data.get("as_info", {}).get("as_name"),
|
|
148
|
+
# "as_number": data.get("as_info", {}).get("as_number"),
|
|
149
|
+
# "as_domain": data.get("as_info", {}).get("as_domain"),
|
|
150
|
+
# "as_cidr": data.get("as_info", {}).get("as_cidr"),
|
|
151
|
+
# "as_usage_type": data.get("as_info", {}).get("as_usage_type"),
|
|
152
|
+
# Continent data
|
|
153
|
+
# "continent_name": data.get("continent", {}).get("name"),
|
|
154
|
+
# "continent_code": data.get("continent", {}).get("code"),
|
|
155
|
+
# "continent_hemisphere": data.get("continent", {}).get("hemisphere"),
|
|
156
|
+
# "continent_translation": data.get("continent", {}).get("translation"),
|
|
157
|
+
# Country data
|
|
158
|
+
# "country_name": data.get("country", {}).get("name"),
|
|
159
|
+
# "country_alpha3_code": data.get("country", {}).get("alpha3_code"),
|
|
160
|
+
# "country_numeric_code": data.get("country", {}).get("numeric_code"),
|
|
161
|
+
# "country_demonym": data.get("country", {}).get("demonym"),
|
|
162
|
+
# "country_flag": data.get("country", {}).get("flag"),
|
|
163
|
+
# "country_capital": data.get("country", {}).get("capital"),
|
|
164
|
+
# "country_total_area": data.get("country", {}).get("total_area"),
|
|
165
|
+
# "country_population": data.get("country", {}).get("population"),
|
|
166
|
+
# "country_currency": data.get("country", {}).get("currency"),
|
|
167
|
+
# "country_language": data.get("country", {}).get("language"),
|
|
168
|
+
# "country_tld": data.get("country", {}).get("tld"),
|
|
169
|
+
# "country_translation": data.get("country", {}).get("translation"),
|
|
170
|
+
# Region data
|
|
171
|
+
# "region_name": data.get("region", {}).get("name"),
|
|
172
|
+
# "region_code": data.get("region", {}).get("code"),
|
|
173
|
+
# "region_translation": data.get("region", {}).get("translation"),
|
|
174
|
+
# City data
|
|
175
|
+
# "city_name": data.get("city", {}).get("name"),
|
|
176
|
+
# "city_translation": data.get("city", {}).get("translation"),
|
|
177
|
+
# Time Zone Info data
|
|
178
|
+
# "time_zone_olson": data.get("time_zone_info", {}).get("olson"),
|
|
179
|
+
# "time_zone_current_time": data.get("time_zone_info", {}).get("current_time"),
|
|
180
|
+
# "time_zone_gmt_offset": data.get("time_zone_info", {}).get("gmt_offset"),
|
|
181
|
+
# "time_zone_is_dst": data.get("time_zone_info", {}).get("is_dst"),
|
|
182
|
+
# "time_zone_abbreviation": data.get("time_zone_info", {}).get("abbreviation"),
|
|
183
|
+
# "time_zone_dst_start_date": data.get("time_zone_info", {}).get("dst_start_date"),
|
|
184
|
+
# "time_zone_dst_end_date": data.get("time_zone_info", {}).get("dst_end_date"),
|
|
185
|
+
# "time_zone_sunrise": data.get("time_zone_info", {}).get("sunrise"),
|
|
186
|
+
# "time_zone_sunset": data.get("time_zone_info", {}).get("sunset"),
|
|
187
|
+
# Geotargeting data
|
|
188
|
+
# "geotargeting_metro": data.get("geotargeting", {}).get("metro"),
|
|
189
|
+
"is_proxy": data.get("is_proxy"),
|
|
190
|
+
"fraud_score": data.get("fraud_score"),
|
|
191
|
+
# Proxy data
|
|
192
|
+
"proxy_last_seen": data.get("proxy", {}).get("last_seen"),
|
|
193
|
+
"proxy_type": data.get("proxy", {}).get("proxy_type"),
|
|
194
|
+
"proxy_threat": data.get("proxy", {}).get("threat"),
|
|
195
|
+
"proxy_provider": data.get("proxy", {}).get("provider"),
|
|
196
|
+
"proxy_is_vpn": data.get("proxy", {}).get("is_vpn"),
|
|
197
|
+
"proxy_is_tor": data.get("proxy", {}).get("is_tor"),
|
|
198
|
+
"proxy_is_data_center": data.get("proxy", {}).get("is_data_center"),
|
|
199
|
+
"proxy_is_public_proxy": data.get("proxy", {}).get("is_public_proxy"),
|
|
200
|
+
"proxy_is_web_proxy": data.get("proxy", {}).get("is_web_proxy"),
|
|
201
|
+
"proxy_is_web_crawler": data.get("proxy", {}).get("is_web_crawler"),
|
|
202
|
+
"proxy_is_ai_crawler": data.get("proxy", {}).get("is_ai_crawler"),
|
|
203
|
+
"proxy_is_residential_proxy": data.get("proxy", {}).get("is_residential_proxy"),
|
|
204
|
+
"proxy_is_spammer": data.get("proxy", {}).get("is_spammer"),
|
|
205
|
+
"proxy_is_scanner": data.get("proxy", {}).get("is_scanner"),
|
|
206
|
+
"proxy_is_botnet": data.get("proxy", {}).get("is_botnet"),
|
|
207
|
+
"proxy_is_bogon": data.get("proxy", {}).get("is_bogon"),
|
|
208
|
+
"proxy_is_consumer_privacy_network": data.get("proxy", {}).get("is_consumer_privacy_network"),
|
|
209
|
+
"proxy_is_enterprise_private_network": data.get("proxy", {}).get("is_enterprise_private_network"),
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
except Exception as e:
|
|
213
|
+
proxy_data["error"] = f"Lookup failed: {str(e)}"
|
|
214
|
+
|
|
215
|
+
# Inject into the FastAPI request state with the generic 'proxy' key
|
|
216
|
+
request.state.proxy = proxy_data
|
|
217
|
+
|
|
218
|
+
# Continue the request lifecycle
|
|
219
|
+
return await call_next(request)
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fastapi-ip2proxy
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A FastAPI middleware SDK for the IP2Proxy Python library.
|
|
5
|
+
Author-email: IP2Location <support@ip2location.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ip2location/fastapi-ip2proxy
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/ip2location/fastapi-ip2proxy/issues
|
|
9
|
+
Keywords: fastapi,ip2proxy,proxy,middleware,ip
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Framework :: FastAPI
|
|
19
|
+
Classifier: Intended Audience :: Developers
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware
|
|
21
|
+
Requires-Python: >=3.8
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE.TXT
|
|
24
|
+
Requires-Dist: fastapi>=0.68.0
|
|
25
|
+
Requires-Dist: starlette>=0.14.0
|
|
26
|
+
Requires-Dist: IP2Proxy>=3.6.1
|
|
27
|
+
Requires-Dist: httpx>=0.24.0
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
30
|
+
Requires-Dist: python-dotenv>=1.0.0; extra == "dev"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# FastAPI IP2Location Middleware
|
|
34
|
+

|
|
35
|
+
|
|
36
|
+
A high-performance, asynchronous FastAPI middleware that automatically geolocates incoming requests using the [IP2Location](https://www.ip2location.com/database/proxy) database or the [IP2Location.io](https://www.ip2location.io/) API. It seamlessly injects the geolocation data directly into the `request.state.location` object for easy access in your route handlers.
|
|
37
|
+
|
|
38
|
+
## Features
|
|
39
|
+
|
|
40
|
+
- **Dual Mode Support**: Use a local `.BIN` database for ultra-fast, zero-latency lookups, or use the IP2Location.io API if you don't want to host the database.
|
|
41
|
+
- **Async & Connection Pooling**: Built with `httpx` for non-blocking API calls, utilizing connection pooling to ensure high throughput.
|
|
42
|
+
- **Proxy Aware**: Automatically extracts the real client IP from headers like `X-Forwarded-For` or `X-Real-IP` when deployed behind load balancers or reverse proxies (like Nginx, Cloudflare, or AWS ALB).
|
|
43
|
+
- **Local Development Friendly**: Includes a `test_ip` parameter to easily override `127.0.0.1` and test specific geographic locations locally.
|
|
44
|
+
- **Multilingual Support**: Supports the `language` parameter (API mode) to return localized names for countries, regions, and cities.
|
|
45
|
+
- **Graceful Degradation**: Never crashes your app. If a lookup fails, it safely injects an error message into the state object so your app can decide how to handle it.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
Install the package via pip:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install fastapi-ip2proxy
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Prerequisites
|
|
56
|
+
|
|
57
|
+
You need at least one of the following to use this middleware:
|
|
58
|
+
|
|
59
|
+
- Local Database (.BIN): Download a free IP2Proxy Lite database (e.g., PX12) from [IP2Location Lite](https://www.ip2location.com/database/lite).
|
|
60
|
+
|
|
61
|
+
- API Key: Sign up for an API key at IP2Location.io.
|
|
62
|
+
|
|
63
|
+
## Usage Examples
|
|
64
|
+
|
|
65
|
+
1. Using the Local Database (Recommended for Production)
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from fastapi import FastAPI, Request
|
|
69
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
70
|
+
|
|
71
|
+
app = FastAPI()
|
|
72
|
+
|
|
73
|
+
app.add_middleware(
|
|
74
|
+
IP2ProxyMiddleware,
|
|
75
|
+
bin_path="IP2PROXY-LITE-PX12.BIN", # Path to your downloaded .BIN file
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@app.get("/")
|
|
79
|
+
async def get_location(request: Request):
|
|
80
|
+
return {"your_location": request.state.proxy}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
2. Using the IP2Location.io API
|
|
84
|
+
```python
|
|
85
|
+
import os
|
|
86
|
+
from fastapi import FastAPI, Request
|
|
87
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
88
|
+
|
|
89
|
+
app = FastAPI()
|
|
90
|
+
|
|
91
|
+
app.add_middleware(
|
|
92
|
+
IP2ProxyMiddleware,
|
|
93
|
+
api_key=os.getenv("IP2LOCATION_API_KEY")
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
@app.get("/")
|
|
97
|
+
async def get_location(request: Request):
|
|
98
|
+
return {"your_location": request.state.proxy}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Advanced Configuration
|
|
102
|
+
|
|
103
|
+
You can fully customize the middleware to suit your environment:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
app.add_middleware(
|
|
107
|
+
IP2ProxyMiddleware,
|
|
108
|
+
bin_path="IP2PROXY-LITE-PX12.BIN",
|
|
109
|
+
api_key="OPTIONAL_FALLBACK_KEY",
|
|
110
|
+
|
|
111
|
+
# Checks these headers first for the real IP.
|
|
112
|
+
# Defaults to ["X-Forwarded-For", "X-Real-IP"]
|
|
113
|
+
ip_headers=["X-Forwarded-For", "X-Real-IP", "CF-Connecting-IP"],
|
|
114
|
+
|
|
115
|
+
# If the user connects from localhost (127.0.0.1), pretend they are
|
|
116
|
+
# connecting from this IP instead. Great for local testing!
|
|
117
|
+
test_ip="8.8.8.8",
|
|
118
|
+
|
|
119
|
+
# Translate country/city names (Requires API mode and a supported plan)
|
|
120
|
+
language="fr"
|
|
121
|
+
)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Accessing the Data
|
|
125
|
+
|
|
126
|
+
The middleware standardizes the output regardless of whether you use the .BIN file or the API. The dictionary injected into request.state.proxy includes the following keys:
|
|
127
|
+
|
|
128
|
+
```json
|
|
129
|
+
{
|
|
130
|
+
"ip": "8.8.8.8",
|
|
131
|
+
"country_short": "US",
|
|
132
|
+
"country_long": "United States",
|
|
133
|
+
"region": "California",
|
|
134
|
+
"city": "Mountain View",
|
|
135
|
+
"asn": "15169",
|
|
136
|
+
"as": "Google LLC",
|
|
137
|
+
"is_proxy": false,
|
|
138
|
+
"error": null
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
*(Note: Premium data fields like proxy data will also be populated if your specific .BIN file or API plan supports them).*
|
|
143
|
+
|
|
144
|
+
## License
|
|
145
|
+
|
|
146
|
+
This project is licensed under the MIT License.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE.TXT
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
fastapi_ip2proxy/__init__.py
|
|
5
|
+
fastapi_ip2proxy/middleware.py
|
|
6
|
+
fastapi_ip2proxy.egg-info/PKG-INFO
|
|
7
|
+
fastapi_ip2proxy.egg-info/SOURCES.txt
|
|
8
|
+
fastapi_ip2proxy.egg-info/dependency_links.txt
|
|
9
|
+
fastapi_ip2proxy.egg-info/requires.txt
|
|
10
|
+
fastapi_ip2proxy.egg-info/top_level.txt
|
|
11
|
+
tests/test_middleware.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fastapi_ip2proxy
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "fastapi-ip2proxy"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "A FastAPI middleware SDK for the IP2Proxy Python library."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "IP2Location", email = "support@ip2location.com" }
|
|
13
|
+
]
|
|
14
|
+
keywords = ["fastapi", "ip2proxy", "proxy", "middleware", "ip"]
|
|
15
|
+
license = "MIT"
|
|
16
|
+
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.8",
|
|
20
|
+
"Programming Language :: Python :: 3.9",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Operating System :: OS Independent",
|
|
26
|
+
"Framework :: FastAPI",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
dependencies = [
|
|
32
|
+
"fastapi>=0.68.0",
|
|
33
|
+
"starlette>=0.14.0",
|
|
34
|
+
"IP2Proxy>=3.6.1",
|
|
35
|
+
"httpx>=0.24.0"
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
dev = [
|
|
40
|
+
"pytest>=7.0.0",
|
|
41
|
+
"python-dotenv>=1.0.0"
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
[project.urls]
|
|
45
|
+
"Homepage" = "https://github.com/ip2location/fastapi-ip2proxy"
|
|
46
|
+
"Bug Tracker" = "https://github.com/ip2location/fastapi-ip2proxy/issues"
|
|
47
|
+
|
|
48
|
+
[tool.setuptools]
|
|
49
|
+
packages = ["fastapi_ip2proxy"]
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from fastapi import FastAPI, Request
|
|
3
|
+
from fastapi.testclient import TestClient
|
|
4
|
+
from unittest.mock import patch, MagicMock, AsyncMock
|
|
5
|
+
|
|
6
|
+
from fastapi_ip2proxy import IP2ProxyMiddleware
|
|
7
|
+
|
|
8
|
+
# --- HELPER FACTORY ---
|
|
9
|
+
def create_test_app(**middleware_kwargs):
|
|
10
|
+
app = FastAPI()
|
|
11
|
+
app.add_middleware(IP2ProxyMiddleware, **middleware_kwargs)
|
|
12
|
+
|
|
13
|
+
@app.get("/")
|
|
14
|
+
async def root(request: Request):
|
|
15
|
+
return request.state.proxy
|
|
16
|
+
|
|
17
|
+
return app
|
|
18
|
+
|
|
19
|
+
# --- TEST 1: BIN MODE ---
|
|
20
|
+
@patch("os.path.exists", return_value=True)
|
|
21
|
+
@patch("IP2Proxy.IP2Proxy")
|
|
22
|
+
def test_middleware_bin_mode(mock_ip2proxy_class, mock_exists):
|
|
23
|
+
mock_db_instance = MagicMock()
|
|
24
|
+
mock_record = MagicMock()
|
|
25
|
+
# mock_record.country_short = "US"
|
|
26
|
+
# mock_record.country_long = "United States"
|
|
27
|
+
# mock_record.city = "Mountain View"
|
|
28
|
+
# mock_record.proxy_type = "DCH"
|
|
29
|
+
# mock_record.is_proxy = 2
|
|
30
|
+
# mock_record.fraud_score = 0
|
|
31
|
+
# mock_db_instance.get_all.return_value = mock_record
|
|
32
|
+
mock_db_instance.get_all.return_value = {
|
|
33
|
+
"country_short": "US",
|
|
34
|
+
"country_long": "United States",
|
|
35
|
+
"city": "Mountain View",
|
|
36
|
+
"proxy_type": "DCH",
|
|
37
|
+
"is_proxy": 2,
|
|
38
|
+
"fraud_score": 0,
|
|
39
|
+
}
|
|
40
|
+
mock_ip2proxy_class.return_value = mock_db_instance
|
|
41
|
+
|
|
42
|
+
app = create_test_app(bin_path="dummy_database.bin", test_ip="8.8.8.8")
|
|
43
|
+
client = TestClient(app)
|
|
44
|
+
|
|
45
|
+
# FIX: Send a local IP header so the middleware triggers the test_ip override
|
|
46
|
+
response = client.get("/", headers={"X-Forwarded-For": "127.0.0.1"})
|
|
47
|
+
assert response.status_code == 200
|
|
48
|
+
|
|
49
|
+
data = response.json()
|
|
50
|
+
assert data["ip"] == "8.8.8.8"
|
|
51
|
+
assert data["country_short"] == "US"
|
|
52
|
+
assert data["city"] == "Mountain View"
|
|
53
|
+
assert data["proxy_type"] == "DCH"
|
|
54
|
+
assert data["error"] is None
|
|
55
|
+
|
|
56
|
+
# --- TEST 2: API MODE ---
|
|
57
|
+
@patch("httpx.AsyncClient.get", new_callable=AsyncMock)
|
|
58
|
+
def test_middleware_api_mode(mock_http_get):
|
|
59
|
+
mock_response = MagicMock()
|
|
60
|
+
mock_response.json.return_value = {
|
|
61
|
+
"country_code": "JP",
|
|
62
|
+
"country_name": "Japan",
|
|
63
|
+
"city_name": "Tokyo",
|
|
64
|
+
"proxy": {"proxy_type": "DCH"},
|
|
65
|
+
# "continent": {"name": "Asia", "code": "AS"}
|
|
66
|
+
}
|
|
67
|
+
mock_response.raise_for_status.return_value = None
|
|
68
|
+
mock_http_get.return_value = mock_response
|
|
69
|
+
|
|
70
|
+
app = create_test_app(api_key="dummy_api_key", test_ip="8.8.8.8", language="ja")
|
|
71
|
+
client = TestClient(app)
|
|
72
|
+
|
|
73
|
+
# FIX: Send a local IP header so the middleware triggers the test_ip override
|
|
74
|
+
response = client.get("/", headers={"X-Forwarded-For": "127.0.0.1"})
|
|
75
|
+
assert response.status_code == 200
|
|
76
|
+
|
|
77
|
+
data = response.json()
|
|
78
|
+
assert data["ip"] == "8.8.8.8"
|
|
79
|
+
assert data["country_short"] == "JP"
|
|
80
|
+
assert data["country_long"] == "Japan"
|
|
81
|
+
assert data["city"] == "Tokyo"
|
|
82
|
+
assert data["proxy_type"] == "DCH"
|
|
83
|
+
# assert data["continent_name"] == "Asia"
|
|
84
|
+
assert data["error"] is None
|
|
85
|
+
|
|
86
|
+
# --- TEST 3: VALIDATION ERROR ---
|
|
87
|
+
def test_middleware_missing_config():
|
|
88
|
+
app = FastAPI()
|
|
89
|
+
|
|
90
|
+
# FIX: Instantiate the middleware directly to test its __init__ logic
|
|
91
|
+
# instead of relying on FastAPI's lazy test client lifecycle.
|
|
92
|
+
with pytest.raises(ValueError, match="Configuration Error"):
|
|
93
|
+
IP2ProxyMiddleware(app=app)
|