ipregistry 3.2.0__tar.gz → 4.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.
@@ -1,27 +1,28 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ipregistry
3
- Version: 3.2.0
3
+ Version: 4.0.0
4
4
  Summary: Official Python library for Ipregistry
5
5
  Home-page: https://ipregistry.co
6
6
  License: Apache-2.0
7
7
  Keywords: ipinfo,ipregistry,ip-address,ip-data,ip-geolocation,threat-detection,user-agent-parsing
8
8
  Author: Ipregistry Team
9
9
  Author-email: support@ipregistry.co
10
- Requires-Python: >=3.6,<4.0
10
+ Requires-Python: >=3.8
11
11
  Classifier: License :: OSI Approved :: Apache Software License
12
12
  Classifier: Programming Language :: Python :: 3
13
- Classifier: Programming Language :: Python :: 3.10
14
- Classifier: Programming Language :: Python :: 3.6
15
- Classifier: Programming Language :: Python :: 3.7
16
13
  Classifier: Programming Language :: Python :: 3.8
17
14
  Classifier: Programming Language :: Python :: 3.9
18
- Requires-Dist: cachetools (>=4.2.4,<5.0.0)
19
- Requires-Dist: requests (>=2.26.0,<3.0.0)
20
- Requires-Dist: six (>=1.16.0,<2.0.0)
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Dist: cachetools (>=5.3.3,<6.0.0)
19
+ Requires-Dist: pydantic (>=2.7.3,<3.0.0)
20
+ Requires-Dist: requests (>=2.32.3,<3.0.0)
21
+ Requires-Dist: tenacity (>=8.3.0,<9.0.0)
21
22
  Project-URL: Repository, https://github.com/ipregistry/ipregistry-python
22
23
  Description-Content-Type: text/markdown
23
24
 
24
- [<img src="https://cdn.ipregistry.co/icons/icon-72x72.png" alt="Ipregistry" width="64"/>](https://ipregistry.co/)
25
+ [<img src="https://cdn.ipregistry.co/icons/favicon-96x96.png" alt="Ipregistry" width="64"/>](https://ipregistry.co/)
25
26
  # Ipregistry Python Client Library
26
27
 
27
28
  [![License](http://img.shields.io/:license-apache-blue.svg)](LICENSE)
@@ -52,8 +53,29 @@ pip install ipregistry
52
53
  from ipregistry import IpregistryClient
53
54
 
54
55
  client = IpregistryClient("YOUR_API_KEY")
55
- ipInfo = client.lookup("54.85.132.205")
56
- print(ipInfo)
56
+ response = client.lookup_ip("54.85.132.205")
57
+
58
+ # Printing whole response
59
+ print(response)
60
+
61
+ # Retrieving a specific field
62
+ country_code = response.data.location.country.code
63
+
64
+ # Getting number of credits consumed or remaining
65
+ credits_consumed = response.credits.consumed
66
+ credits_remaining = response.credits.remaining
67
+ ```
68
+
69
+ #### Single ASN Lookup
70
+
71
+ ```python
72
+ from ipregistry import IpregistryClient
73
+
74
+ client = IpregistryClient("YOUR_API_KEY")
75
+ response = client.lookup_asn(42)
76
+ print(response.credits.consumed)
77
+ print(response.data.prefixes)
78
+ print(response.data.relationships)
57
79
  ```
58
80
 
59
81
  #### Batch IP Lookup
@@ -62,9 +84,9 @@ print(ipInfo)
62
84
  from ipregistry import IpregistryClient
63
85
 
64
86
  client = IpregistryClient("YOUR_API_KEY")
65
- results = client.lookup(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
66
- for ipInfo in results:
67
- print(ipInfo)
87
+ response = client.batch_lookup_ips(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
88
+ for ip_info in response.data:
89
+ print(ip_info)
68
90
  ```
69
91
 
70
92
  #### Origin IP Lookup
@@ -73,8 +95,18 @@ for ipInfo in results:
73
95
  from ipregistry import IpregistryClient
74
96
 
75
97
  client = IpregistryClient("YOUR_API_KEY")
76
- ipInfo = client.lookup()
77
- print(ipInfo)
98
+ response = client.origin_lookup_ip()
99
+ print(response.data)
100
+ ```
101
+
102
+ #### User-Agent Parsing
103
+
104
+ ```python
105
+ from ipregistry import IpregistryClient
106
+
107
+ client = IpregistryClient("YOUR_API_KEY")
108
+ response = client.parse_user_agent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36')
109
+ print(response.data)
78
110
  ```
79
111
 
80
112
  More advanced examples are available in the [samples](https://github.com/ipregistry/ipregistry-python/tree/master/samples)
@@ -106,6 +138,18 @@ from ipregistry import IpregistryClient, NoCache
106
138
  client = IpregistryClient("YOUR_API_KEY", cache=NoCache())
107
139
  ```
108
140
 
141
+ ### European Union Base URL
142
+
143
+ With the ever-increasing concerns about data privacy and security, we recognize the importance of providing our European users with a dedicated API base URL:
144
+
145
+ ```python
146
+ from ipregistry import IpregistryClient, NoCache
147
+
148
+ client = IpregistryClient(IpregistryConfig("YOUR_API_KEY").with_eu_base_url())
149
+ ```
150
+
151
+ Using this base URL your requests are handled by the closest cluster of nodes in the European Union.
152
+
109
153
  ### Errors
110
154
 
111
155
  All Ipregistry exceptions inherit `IpregistryError` class.
@@ -122,9 +166,9 @@ A manner to proceed is to identify bots using the `User-Agent` header.
122
166
  To ease this process, the library includes a utility method:
123
167
 
124
168
  ```python
125
- from ipregistry import UserAgent
169
+ from ipregistry import UserAgents
126
170
 
127
- isBot = UserAgent.isBot('YOUR_USER_AGENT_HEADER_VALUE_HERE')
171
+ is_bot = UserAgents.is_bot('YOUR_USER_AGENT_HEADER_VALUE_HERE')
128
172
  ```
129
173
 
130
174
  ## Other Libraries
@@ -1,4 +1,4 @@
1
- [<img src="https://cdn.ipregistry.co/icons/icon-72x72.png" alt="Ipregistry" width="64"/>](https://ipregistry.co/)
1
+ [<img src="https://cdn.ipregistry.co/icons/favicon-96x96.png" alt="Ipregistry" width="64"/>](https://ipregistry.co/)
2
2
  # Ipregistry Python Client Library
3
3
 
4
4
  [![License](http://img.shields.io/:license-apache-blue.svg)](LICENSE)
@@ -29,8 +29,29 @@ pip install ipregistry
29
29
  from ipregistry import IpregistryClient
30
30
 
31
31
  client = IpregistryClient("YOUR_API_KEY")
32
- ipInfo = client.lookup("54.85.132.205")
33
- print(ipInfo)
32
+ response = client.lookup_ip("54.85.132.205")
33
+
34
+ # Printing whole response
35
+ print(response)
36
+
37
+ # Retrieving a specific field
38
+ country_code = response.data.location.country.code
39
+
40
+ # Getting number of credits consumed or remaining
41
+ credits_consumed = response.credits.consumed
42
+ credits_remaining = response.credits.remaining
43
+ ```
44
+
45
+ #### Single ASN Lookup
46
+
47
+ ```python
48
+ from ipregistry import IpregistryClient
49
+
50
+ client = IpregistryClient("YOUR_API_KEY")
51
+ response = client.lookup_asn(42)
52
+ print(response.credits.consumed)
53
+ print(response.data.prefixes)
54
+ print(response.data.relationships)
34
55
  ```
35
56
 
36
57
  #### Batch IP Lookup
@@ -39,9 +60,9 @@ print(ipInfo)
39
60
  from ipregistry import IpregistryClient
40
61
 
41
62
  client = IpregistryClient("YOUR_API_KEY")
42
- results = client.lookup(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
43
- for ipInfo in results:
44
- print(ipInfo)
63
+ response = client.batch_lookup_ips(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
64
+ for ip_info in response.data:
65
+ print(ip_info)
45
66
  ```
46
67
 
47
68
  #### Origin IP Lookup
@@ -50,8 +71,18 @@ for ipInfo in results:
50
71
  from ipregistry import IpregistryClient
51
72
 
52
73
  client = IpregistryClient("YOUR_API_KEY")
53
- ipInfo = client.lookup()
54
- print(ipInfo)
74
+ response = client.origin_lookup_ip()
75
+ print(response.data)
76
+ ```
77
+
78
+ #### User-Agent Parsing
79
+
80
+ ```python
81
+ from ipregistry import IpregistryClient
82
+
83
+ client = IpregistryClient("YOUR_API_KEY")
84
+ response = client.parse_user_agent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36')
85
+ print(response.data)
55
86
  ```
56
87
 
57
88
  More advanced examples are available in the [samples](https://github.com/ipregistry/ipregistry-python/tree/master/samples)
@@ -83,6 +114,18 @@ from ipregistry import IpregistryClient, NoCache
83
114
  client = IpregistryClient("YOUR_API_KEY", cache=NoCache())
84
115
  ```
85
116
 
117
+ ### European Union Base URL
118
+
119
+ With the ever-increasing concerns about data privacy and security, we recognize the importance of providing our European users with a dedicated API base URL:
120
+
121
+ ```python
122
+ from ipregistry import IpregistryClient, NoCache
123
+
124
+ client = IpregistryClient(IpregistryConfig("YOUR_API_KEY").with_eu_base_url())
125
+ ```
126
+
127
+ Using this base URL your requests are handled by the closest cluster of nodes in the European Union.
128
+
86
129
  ### Errors
87
130
 
88
131
  All Ipregistry exceptions inherit `IpregistryError` class.
@@ -99,9 +142,9 @@ A manner to proceed is to identify bots using the `User-Agent` header.
99
142
  To ease this process, the library includes a utility method:
100
143
 
101
144
  ```python
102
- from ipregistry import UserAgent
145
+ from ipregistry import UserAgents
103
146
 
104
- isBot = UserAgent.isBot('YOUR_USER_AGENT_HEADER_VALUE_HERE')
147
+ is_bot = UserAgents.is_bot('YOUR_USER_AGENT_HEADER_VALUE_HERE')
105
148
  ```
106
149
 
107
150
  ## Other Libraries
@@ -1,9 +1,8 @@
1
1
  name = "ipregistry"
2
2
 
3
- from .version import __version__
4
-
5
3
  from .cache import *
6
4
  from .core import *
5
+ from .json import *
7
6
  from .model import *
8
7
  from .request import *
9
8
  from .util import *
@@ -14,28 +14,28 @@
14
14
  limitations under the License.
15
15
  """
16
16
 
17
- import abc, six
18
-
17
+ from abc import ABC, abstractmethod
19
18
  from cachetools import TTLCache
20
19
 
21
- @six.add_metaclass(abc.ABCMeta)
22
- class IpregistryCache:
23
- @abc.abstractmethod
20
+
21
+ class IpregistryCache(ABC):
22
+ @abstractmethod
24
23
  def get(self, key):
25
24
  pass
26
25
 
27
- @abc.abstractmethod
26
+ @abstractmethod
28
27
  def put(self, key, data):
29
28
  pass
30
29
 
31
- @abc.abstractmethod
30
+ @abstractmethod
32
31
  def invalidate(self, key):
33
32
  pass
34
33
 
35
- @abc.abstractmethod
36
- def invalidateAll(self):
34
+ @abstractmethod
35
+ def invalidate_all(self):
37
36
  pass
38
37
 
38
+
39
39
  class InMemoryCache(IpregistryCache):
40
40
  def __init__(self, maxsize=2048, ttl=600):
41
41
  self._cache = TTLCache(maxsize, ttl)
@@ -52,10 +52,11 @@ class InMemoryCache(IpregistryCache):
52
52
  def invalidate(self, key):
53
53
  del self._cache[key]
54
54
 
55
- def invalidateAll(self):
55
+ def invalidate_all(self):
56
56
  for key in self._cache:
57
57
  del self._cache[key]
58
58
 
59
+
59
60
  class NoCache(IpregistryCache):
60
61
  def __init__(self, maxsize=2048, ttl=86400):
61
62
  pass
@@ -69,5 +70,5 @@ class NoCache(IpregistryCache):
69
70
  def invalidate(self, key):
70
71
  pass
71
72
 
72
- def invalidateAll(self):
73
+ def invalidate_all(self):
73
74
  pass
@@ -0,0 +1,183 @@
1
+ """
2
+ Copyright 2019 Ipregistry (https://ipregistry.co).
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ https://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ """
16
+ from .cache import IpregistryCache, NoCache
17
+ from .json import AutonomousSystem, IpInfo
18
+ from .model import LookupError, ApiResponse, ApiResponseCredits, ApiResponseThrottling
19
+ from .request import DefaultRequestHandler, IpregistryRequestHandler
20
+
21
+
22
+ class IpregistryClient:
23
+ def __init__(self, key_or_config, **kwargs):
24
+ self._config = key_or_config if isinstance(key_or_config, IpregistryConfig) else IpregistryConfig(key_or_config)
25
+ self._cache = kwargs["cache"] if "cache" in kwargs else NoCache()
26
+ self._requestHandler = kwargs["requestHandler"] if "requestHandler" in kwargs else DefaultRequestHandler(self._config)
27
+
28
+ if not isinstance(self._cache, IpregistryCache):
29
+ raise ValueError("Given cache instance is not of type IpregistryCache")
30
+ if not isinstance(self._requestHandler, IpregistryRequestHandler):
31
+ raise ValueError("Given request handler instance is not of type IpregistryRequestHandler")
32
+
33
+ def batch_lookup_asns(self, ips, **options):
34
+ return self.batch_request(ips, self._requestHandler.batch_lookup_asns, **options)
35
+
36
+ def batch_lookup_ips(self, ips, **options):
37
+ return self.batch_request(ips, self._requestHandler.batch_lookup_ips, **options)
38
+
39
+ def batch_parse_user_agents(self, user_agents, **options):
40
+ return self.batch_request(user_agents, self._requestHandler.batch_parse_user_agents, **options)
41
+
42
+ def batch_request(self, items, request_handler_func, **options):
43
+ sparse_cache = [None] * len(items)
44
+ cache_misses = []
45
+
46
+ for i in range(len(items)):
47
+ item = items[i]
48
+ cache_key = self.__build_cache_key(item, options)
49
+ cache_value = self._cache.get(cache_key)
50
+ if cache_value is None:
51
+ cache_misses.append(item)
52
+ else:
53
+ sparse_cache[i] = cache_value
54
+
55
+ result = [None] * len(items)
56
+ if len(cache_misses) > 0:
57
+ response = request_handler_func(cache_misses, options)
58
+ else:
59
+ response = ApiResponse(
60
+ ApiResponseCredits(),
61
+ [],
62
+ ApiResponseThrottling()
63
+ )
64
+
65
+ fresh_item_info = response.data
66
+ j = 0
67
+ k = 0
68
+
69
+ for cached_item_info in sparse_cache:
70
+ if cached_item_info is None:
71
+ if not isinstance(fresh_item_info[k], LookupError):
72
+ self._cache.put(self.__build_cache_key(items[j], options), fresh_item_info[k])
73
+ result[j] = fresh_item_info[k]
74
+ k += 1
75
+ else:
76
+ result[j] = cached_item_info
77
+ j += 1
78
+
79
+ response.data = result
80
+
81
+ return response
82
+
83
+ def lookup_asn(self, asn, **options):
84
+ return self.__lookup_asn(asn, options)
85
+
86
+ def lookup_ip(self, ip, **options):
87
+ if isinstance(ip, str):
88
+ return self.__lookup_ip(ip, options)
89
+ else:
90
+ raise ValueError("Invalid value for 'ip' parameter: " + ip)
91
+
92
+ def origin_lookup_asn(self, **options):
93
+ return self.__lookup_asn('AS', options)
94
+
95
+ def origin_lookup_ip(self, **options):
96
+ return self.__lookup_ip('', options)
97
+
98
+ def origin_parse_user_agent(self, **options):
99
+ return self._requestHandler.origin_parse_user_agent(options)
100
+
101
+ def __lookup_asn(self, asn, options):
102
+ return self.__lookup(
103
+ 'AS' + str(asn) if IpregistryClient.__is_number(asn) else 'AS',
104
+ options, self._requestHandler.lookup_asn,
105
+ AutonomousSystem)
106
+
107
+ def __lookup_ip(self, ip, options):
108
+ return self.__lookup(ip, options, self._requestHandler.lookup_ip, IpInfo)
109
+
110
+ def __lookup(self, key, options, lookup_func, response_type):
111
+ cache_key = self.__build_cache_key(key, options)
112
+ cache_value = self._cache.get(cache_key)
113
+
114
+ if cache_value is None:
115
+ response = lookup_func(key, options)
116
+ if isinstance(response.data, response_type):
117
+ self._cache.put(cache_key, response.data)
118
+ return response
119
+
120
+ return ApiResponse(
121
+ ApiResponseCredits(),
122
+ cache_value,
123
+ ApiResponseThrottling()
124
+ )
125
+
126
+ def parse_user_agent(self, user_agent, **options):
127
+ response = self.batch_parse_user_agents([user_agent], **options)
128
+ response.data = response.data[0]
129
+ return response
130
+
131
+ @staticmethod
132
+ def __build_cache_key(key, options):
133
+ result = key
134
+
135
+ for key, value in options.items():
136
+ if isinstance(value, bool):
137
+ value = 'true' if value is True else 'false'
138
+ result += ';' + key + '=' + value
139
+
140
+ return result
141
+
142
+ @staticmethod
143
+ def __is_api_error(data):
144
+ return 'code' in data
145
+
146
+ @staticmethod
147
+ def __is_number(value):
148
+ try:
149
+ # Try converting the value to a float
150
+ float(value)
151
+ return True
152
+ except ValueError:
153
+ return False
154
+
155
+
156
+ class IpregistryConfig:
157
+ def __init__(self, key, base_url="https://api.ipregistry.co", timeout=5):
158
+ """
159
+ Initialize the IpregistryConfig instance.
160
+
161
+ Parameters:
162
+ key (str): The API key for accessing the Ipregistry service.
163
+ base_url (str): The base URL for the Ipregistry API. Defaults to "https://api.ipregistry.co".
164
+ There also exists a European Union (EU) base URL "https://eu.api.ipregistry.co"
165
+ that can be used to ensure requests are handled by nodes hosted in the EU only.
166
+ timeout (int): The timeout duration (in seconds) for API requests. Defaults to 15 seconds.
167
+ """
168
+ self.api_key = key
169
+ self.base_url = base_url
170
+ self.timeout = timeout
171
+
172
+ def with_eu_base_url(self):
173
+ self.base_url = 'https://eu.api.ipregistry.co'
174
+ return self
175
+
176
+ def __str__(self):
177
+ """
178
+ Return a string representation of the IpregistryConfig instance.
179
+
180
+ Returns:
181
+ str: A string containing the API key, base URL, and timeout value.
182
+ """
183
+ return "api_key={}, base_url={}, timeout={}".format(self.api_key, self.base_url, self.timeout)