Skip to content

Commit

Permalink
Use snake case for function and variable names
Browse files Browse the repository at this point in the history
  • Loading branch information
lpellegr committed Jun 10, 2024
1 parent 5d46523 commit 4774c33
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 72 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]
### Changed
- Rename all function and variable names to use snake case.
- Rename _IpregistryConfig_ option `apiUrl` to `baseUrl`.

## [3.2.0] - 2021-11-09
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ pip install ipregistry
from ipregistry import IpregistryClient

client = IpregistryClient("YOUR_API_KEY")
ipInfo = client.lookup("54.85.132.205")
print(ipInfo)
ip_info = client.lookup("54.85.132.205")
print(ip_info)
```

#### Batch IP Lookup
Expand All @@ -40,8 +40,8 @@ from ipregistry import IpregistryClient

client = IpregistryClient("YOUR_API_KEY")
results = client.lookup(["54.85.132.205", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
for ipInfo in results:
print(ipInfo)
for ip_info in results:
print(ip_info)
```

#### Origin IP Lookup
Expand All @@ -50,8 +50,8 @@ for ipInfo in results:
from ipregistry import IpregistryClient

client = IpregistryClient("YOUR_API_KEY")
ipInfo = client.lookup()
print(ipInfo)
ip_info = client.lookup()
print(ip_info)
```

More advanced examples are available in the [samples](https://github.com/ipregistry/ipregistry-python/tree/master/samples)
Expand Down Expand Up @@ -101,7 +101,7 @@ To ease this process, the library includes a utility method:
```python
from ipregistry import UserAgent

isBot = UserAgent.isBot('YOUR_USER_AGENT_HEADER_VALUE_HERE')
is_bot = UserAgent.is_bot('YOUR_USER_AGENT_HEADER_VALUE_HERE')
```

## Other Libraries
Expand Down
6 changes: 3 additions & 3 deletions ipregistry/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def invalidate(self, key):
pass

@abc.abstractmethod
def invalidateAll(self):
def invalidate_all(self):
pass


Expand All @@ -54,7 +54,7 @@ def put(self, key, data):
def invalidate(self, key):
del self._cache[key]

def invalidateAll(self):
def invalidate_all(self):
for key in self._cache:
del self._cache[key]

Expand All @@ -72,5 +72,5 @@ def put(self, key, data):
def invalidate(self, key):
pass

def invalidateAll(self):
def invalidate_all(self):
pass
74 changes: 37 additions & 37 deletions ipregistry/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@


class IpregistryClient:
def __init__(self, keyOrConfig, **kwargs):
self._config = keyOrConfig if isinstance(keyOrConfig, IpregistryConfig) else IpregistryConfig(keyOrConfig)
def __init__(self, key_or_config, **kwargs):
self._config = key_or_config if isinstance(key_or_config, IpregistryConfig) else IpregistryConfig(key_or_config)
self._cache = kwargs["cache"] if "cache" in kwargs else NoCache()
self._requestHandler = kwargs["requestHandler"] if "requestHandler" in kwargs else DefaultRequestHandler(self._config)

Expand All @@ -30,60 +30,60 @@ def __init__(self, keyOrConfig, **kwargs):
if not isinstance(self._requestHandler, IpregistryRequestHandler):
raise ValueError("Given request handler instance is not of type IpregistryRequestHandler")

def lookup(self, ipOrList='', **options):
if ipOrList == '':
return self._originLookup(options)
elif isinstance(ipOrList, list):
return self._batchLookup(ipOrList, options)
elif isinstance(ipOrList, str):
return self._singleLookup(ipOrList, options)
def lookup(self, ip_or_list='', **options):
if ip_or_list == '':
return self._origin_lookup(options)
elif isinstance(ip_or_list, list):
return self._batch_lookup(ip_or_list, options)
elif isinstance(ip_or_list, str):
return self._single_lookup(ip_or_list, options)
else:
raise ValueError("Invalid parameter type")

def _batchLookup(self, ips, options):
sparseCache = [None] * len(ips)
cacheMisses = []
def _batch_lookup(self, ips, options):
sparse_cache = [None] * len(ips)
cache_misses = []

for i in range(0, len(ips)):
ip = ips[i]
cacheKey = self._buildCacheKey(ip, options)
cacheValue = self._cache.get(cacheKey)
if cacheValue is None:
cacheMisses.append(ip)
cache_key = self._build_cache_key(ip, options)
cache_value = self._cache.get(cache_key)
if cache_value is None:
cache_misses.append(ip)
else:
sparseCache[i] = cacheValue
sparse_cache[i] = cache_value

result = [None] * len(ips)
freshIpInfo = self._requestHandler.batchLookup(cacheMisses, options)
fresh_ip_info = self._requestHandler.batch_lookup(cache_misses, options)
j = 0
k = 0

for cachedIpInfo in sparseCache:
for cachedIpInfo in sparse_cache:
if cachedIpInfo is None:
if not isinstance(freshIpInfo[k], LookupError):
self._cache.put(self._buildCacheKey(ips[j], options), freshIpInfo[k])
result[j] = freshIpInfo[k]
if not isinstance(fresh_ip_info[k], LookupError):
self._cache.put(self._build_cache_key(ips[j], options), fresh_ip_info[k])
result[j] = fresh_ip_info[k]
k += 1
else:
result[j] = cachedIpInfo
j += 1

return result

def _originLookup(self, options):
return self._singleLookup('', options)
def _origin_lookup(self, options):
return self._single_lookup('', options)

def _singleLookup(self, ip, options):
cacheKey = self._buildCacheKey(ip, options)
cacheValue = self._cache.get(cacheKey)
def _single_lookup(self, ip, options):
cache_key = self._build_cache_key(ip, options)
cache_value = self._cache.get(cache_key)

if cacheValue is None:
cacheValue = self._requestHandler.singleLookup(ip, options)
self._cache.put(cacheKey, cacheValue)
if cache_value is None:
cache_value = self._requestHandler.single_lookup(ip, options)
self._cache.put(cache_key, cache_value)

return cacheValue
return cache_value

def _buildCacheKey(self, ip, options):
def _build_cache_key(self, ip, options):
result = ip

for key, value in options.items():
Expand All @@ -93,15 +93,15 @@ def _buildCacheKey(self, ip, options):

return result

def _isApiError(self, data):
def _is_api_error(self, data):
return 'code' in data


class IpregistryConfig:
def __init__(self, key, baseUrl="https://api.ipregistry.co", timeout=15):
self.apiKey = key
self.baseUrl = baseUrl
def __init__(self, key, base_url="https://api.ipregistry.co", timeout=15):
self.api_key = key
self.base_url = base_url
self.timeout = timeout

def __str__(self):
return "apiKey={}, baseUrl={}, timeout={}".format(self.apiKey, self.baseUrl, self.timeout)
return "api_key={}, base_url={}, timeout={}".format(self.api_key, self.base_url, self.timeout)
22 changes: 11 additions & 11 deletions ipregistry/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ def __init__(self, config):
self._config = config

@abc.abstractmethod
def batchLookup(self, ips, options):
def batch_lookup(self, ips, options):
pass

@abc.abstractmethod
def originLookup(self, options):
def origin_lookup(self, options):
pass

@abc.abstractmethod
def singleLookup(self, ip, options):
def single_lookup(self, ip, options):
pass

def _buildBaseUrl(self, ip, options):
result = self._config.baseUrl + "/" + ip + "?key=" + self._config.apiKey
def _build_base_url(self, ip, options):
result = self._config.base_url + "/" + ip + "?key=" + self._config.api_key

for key, value in options.items():
if isinstance(value, bool):
Expand All @@ -55,22 +55,22 @@ def _buildBaseUrl(self, ip, options):


class DefaultRequestHandler(IpregistryRequestHandler):
def batchLookup(self, ips, options):
def batch_lookup(self, ips, options):
try:
r = requests.post(self._buildBaseUrl('', options), data=json.dumps(ips), headers=self._headers(), timeout=self._config.timeout)
r = requests.post(self._build_base_url('', options), data=json.dumps(ips), headers=self._headers(), timeout=self._config.timeout)
r.raise_for_status()
return list(map(lambda data: LookupError(data) if 'code' in data else IpInfo(data), r.json()['results']))
except requests.HTTPError:
raise ApiError(r.json())
except Exception as e:
raise ClientError(e)

def originLookup(self, options):
return self.singleLookup('', options)
def origin_lookup(self, options):
return self.single_lookup('', options)

def singleLookup(self, ip, options):
def single_lookup(self, ip, options):
try:
r = requests.get(self._buildBaseUrl(ip, options), headers=self._headers(), timeout=self._config.timeout)
r = requests.get(self._build_base_url(ip, options), headers=self._headers(), timeout=self._config.timeout)
r.raise_for_status()
return IpInfo(r.json())
except requests.HTTPError:
Expand Down
2 changes: 1 addition & 1 deletion ipregistry/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@
class UserAgent:

@staticmethod
def isBot(header):
def is_bot(header):
header = header.lower()
return "bot" in header or "spider" in header
2 changes: 1 addition & 1 deletion tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def test_defaultcache_invalidateAll(self):
cache.put("a", 1)
cache.put("b", 2)
cache.put("c", 3)
cache.invalidateAll()
cache.invalidate_all()
self.assertEqual(None, cache.get("a"))
self.assertEqual(None, cache.get("b"))
self.assertEqual(None, cache.get("c"))
Expand Down
20 changes: 10 additions & 10 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,21 @@ def test_default_config(self):
"""
Test that default config use right parameters
"""
requestHandler = DefaultRequestHandler(IpregistryConfig("tryout"))
print(requestHandler._config)
self.assertEqual("tryout", requestHandler._config.apiKey)
self.assertEqual("https://api.ipregistry.co", requestHandler._config.baseUrl)
self.assertEqual(15, requestHandler._config.timeout)
request_handler = DefaultRequestHandler(IpregistryConfig("tryout"))
print(request_handler._config)
self.assertEqual("tryout", request_handler._config.api_key)
self.assertEqual("https://api.ipregistry.co", request_handler._config.base_url)
self.assertEqual(15, request_handler._config.timeout)

def test_config_optional_parameters(self):
"""
Test that config takes into account optional parameters
"""
requestHandler = DefaultRequestHandler(IpregistryConfig("MY_API_KEY", "https://custom.acme.com", 10))
print(requestHandler._config)
self.assertEqual("MY_API_KEY", requestHandler._config.apiKey)
self.assertEqual("https://custom.acme.com", requestHandler._config.baseUrl)
self.assertEqual(10, requestHandler._config.timeout)
request_handler = DefaultRequestHandler(IpregistryConfig("MY_API_KEY", "https://custom.acme.com", 10))
print(request_handler._config)
self.assertEqual("MY_API_KEY", request_handler._config.api_key)
self.assertEqual("https://custom.acme.com", request_handler._config.base_url)
self.assertEqual(10, request_handler._config.timeout)


if __name__ == '__main__':
Expand Down
4 changes: 2 additions & 2 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ def test_isbot_chrome_false(self):
"""
Test that isBot is False with standard Chrome User-Agent
"""
self.assertEqual(False, UserAgent.isBot("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"))
self.assertEqual(False, UserAgent.is_bot("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"))

def test_isbot_chrome_true(self):
"""
Test that isBot is True with Googlebot UserAgent
"""
self.assertEqual(True, UserAgent.isBot("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"))
self.assertEqual(True, UserAgent.is_bot("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"))


if __name__ == '__main__':
Expand Down

0 comments on commit 4774c33

Please sign in to comment.