0
# Synchronous Handlers
1
2
Synchronous API clients for IP geolocation lookups using the requests library. Provides both Core API and Lite API access with comprehensive configuration options, caching, and batch processing capabilities.
3
4
## Capabilities
5
6
### Handler Factory Functions
7
8
Factory functions that create and return configured handler instances with simplified initialization.
9
10
```python { .api }
11
def getHandler(access_token=None, **kwargs):
12
"""
13
Create and return Handler object for Core API access.
14
15
Parameters:
16
- access_token (str, optional): IPinfo API access token
17
- **kwargs: Additional configuration options
18
19
Returns:
20
Handler: Configured Handler instance
21
"""
22
23
def getHandlerLite(access_token=None, **kwargs):
24
"""
25
Create and return HandlerLite object for Lite API access.
26
27
Parameters:
28
- access_token (str, optional): IPinfo API access token
29
- **kwargs: Additional configuration options
30
31
Returns:
32
HandlerLite: Configured HandlerLite instance
33
"""
34
```
35
36
### Core API Handler
37
38
Primary synchronous client for the IPinfo Core API, supporting single IP lookups, batch operations, and map generation with comprehensive caching and configuration options.
39
40
```python { .api }
41
class Handler:
42
def __init__(self, access_token=None, **kwargs):
43
"""
44
Initialize Handler with configuration options.
45
46
Parameters:
47
- access_token (str, optional): IPinfo API access token
48
- countries (dict, optional): Custom country code to name mappings
49
- eu_countries (list, optional): Custom list of EU country codes
50
- countries_flags (dict, optional): Custom country flag mappings
51
- countries_currencies (dict, optional): Custom country currency mappings
52
- continent (dict, optional): Custom continent mappings
53
- request_options (dict, optional): HTTP request configuration
54
- cache_options (dict, optional): Cache configuration (maxsize, ttl)
55
- cache (CacheInterface, optional): Custom cache implementation
56
- headers (dict, optional): Custom HTTP headers
57
"""
58
59
def getDetails(self, ip_address=None, timeout=None):
60
"""
61
Get details for specified IP address or current IP.
62
63
Parameters:
64
- ip_address (str|IPv4Address|IPv6Address, optional): IP address to lookup
65
- timeout (int, optional): Request timeout override
66
67
Returns:
68
Details: IP address details object
69
70
Raises:
71
RequestQuotaExceededError: When API quota exceeded
72
APIError: When API returns error response
73
"""
74
75
def getBatchDetails(self, ip_addresses, batch_size=None, timeout_per_batch=5, timeout_total=None, raise_on_fail=True):
76
"""
77
Get details for multiple IP addresses in batch requests.
78
79
Parameters:
80
- ip_addresses (list): List of IP addresses to lookup
81
- batch_size (int, optional): Batch size (default: 1000, max: 1000)
82
- timeout_per_batch (int, optional): Timeout per batch request (default: 5)
83
- timeout_total (int, optional): Total operation timeout
84
- raise_on_fail (bool, optional): Whether to raise on errors (default: True)
85
86
Returns:
87
dict: Mapping of IP addresses to Details objects or error info
88
89
Raises:
90
RequestQuotaExceededError: When API quota exceeded
91
TimeoutExceededError: When timeout limits exceeded
92
"""
93
94
def getMap(self, ips):
95
"""
96
Get URL to map visualization for list of IPs.
97
98
Parameters:
99
- ips (list): List of IP addresses (max 500,000)
100
101
Returns:
102
str: URL to map visualization
103
104
Raises:
105
requests.HTTPError: When request fails
106
"""
107
108
def getBatchDetailsIter(self, ip_addresses, batch_size=None, raise_on_fail=True):
109
"""
110
Iterator version of batch details lookup.
111
112
Parameters:
113
- ip_addresses (list): List of IP addresses to lookup
114
- batch_size (int, optional): Batch size (default: 1000)
115
- raise_on_fail (bool, optional): Whether to raise on errors (default: True)
116
117
Yields:
118
Details: IP address details for each batch
119
120
Raises:
121
RequestQuotaExceededError: When API quota exceeded
122
"""
123
```
124
125
### Lite API Handler
126
127
Synchronous client for the IPinfo Lite API, providing simplified IP geolocation data with reduced response fields and faster processing.
128
129
```python { .api }
130
class HandlerLite:
131
def __init__(self, access_token=None, **kwargs):
132
"""
133
Initialize HandlerLite with configuration options.
134
135
Parameters: Same as Handler class
136
"""
137
138
def getDetails(self, ip_address=None, timeout=None):
139
"""
140
Get details for specified IP address using Lite API.
141
142
Parameters:
143
- ip_address (str|IPv4Address|IPv6Address, optional): IP address to lookup
144
- timeout (int, optional): Request timeout override
145
146
Returns:
147
Details: IP address details object with Lite API fields
148
149
Raises:
150
RequestQuotaExceededError: When API quota exceeded
151
APIError: When API returns error response
152
"""
153
```
154
155
## Usage Examples
156
157
### Basic IP Lookup
158
159
```python
160
import ipinfo
161
162
# Create handler
163
handler = ipinfo.getHandler('your_access_token')
164
165
# Single IP lookup
166
details = handler.getDetails('8.8.8.8')
167
print(f"Location: {details.city}, {details.region}, {details.country}")
168
print(f"ISP: {details.org}")
169
print(f"Coordinates: {details.latitude}, {details.longitude}")
170
```
171
172
### Batch Processing
173
174
```python
175
import ipinfo
176
177
handler = ipinfo.getHandler('your_access_token')
178
179
# Batch lookup
180
ips = ['8.8.8.8', '1.1.1.1', '208.67.222.222']
181
results = handler.getBatchDetails(ips)
182
183
for ip, details in results.items():
184
if isinstance(details, dict):
185
print(f"{ip}: {details.get('city', 'Unknown')}")
186
else:
187
print(f"{ip}: {details.city}")
188
```
189
190
### Custom Configuration
191
192
```python
193
import ipinfo
194
195
# Custom cache and timeout settings
196
handler = ipinfo.getHandler(
197
'your_access_token',
198
cache_options={'maxsize': 1000, 'ttl': 3600}, # 1 hour TTL
199
request_options={'timeout': 5},
200
headers={'User-Agent': 'MyApp/1.0'}
201
)
202
203
details = handler.getDetails('8.8.8.8', timeout=10)
204
```
205
206
### Lite API Usage
207
208
```python
209
import ipinfo
210
211
# Use Lite API for faster, simpler responses
212
handler_lite = ipinfo.getHandlerLite('your_access_token')
213
details = handler_lite.getDetails('8.8.8.8')
214
215
print(f"Country: {details.country}") # Country name
216
print(f"Country Code: {details.country_code}") # Country code
217
```
218
219
### Error Handling
220
221
```python
222
import ipinfo
223
from ipinfo.exceptions import RequestQuotaExceededError, TimeoutExceededError
224
from ipinfo.error import APIError
225
226
handler = ipinfo.getHandler('your_access_token')
227
228
try:
229
details = handler.getDetails('8.8.8.8')
230
print(details.city)
231
except RequestQuotaExceededError:
232
print("Monthly quota exceeded")
233
except APIError as e:
234
print(f"API error {e.error_code}: {e.error_json}")
235
except Exception as e:
236
print(f"Unexpected error: {e}")
237
```
238
239
## Types
240
241
```python { .api }
242
# Handler configuration options
243
HandlerOptions = {
244
'countries': dict, # Country code to name mappings
245
'eu_countries': list, # List of EU country codes
246
'countries_flags': dict, # Country flag emoji/unicode info
247
'countries_currencies': dict, # Country currency info
248
'continent': dict, # Continent mappings
249
'request_options': dict, # HTTP request options
250
'cache_options': dict, # Cache configuration
251
'cache': CacheInterface, # Custom cache implementation
252
'headers': dict # Custom HTTP headers
253
}
254
255
# Batch operation result
256
BatchResult = dict # IP address -> Details object or error info
257
258
# Cache configuration
259
CacheOptions = {
260
'maxsize': int, # Maximum cache entries (default: 4096)
261
'ttl': int # Time to live in seconds (default: 86400)
262
}
263
264
# Request configuration
265
RequestOptions = {
266
'timeout': int, # Request timeout in seconds (default: 2)
267
'proxies': dict, # Proxy configuration
268
'verify': bool, # SSL verification
269
'cert': str, # Client certificate
270
'stream': bool # Stream response
271
}
272
```