Skip to content

Commit

Permalink
Merge pull request #13 from ipinfo/uman/fix-deps
Browse files Browse the repository at this point in the history
Fix missing `six` dependency
  • Loading branch information
UmanShahzad committed May 31, 2019
2 parents 62fef91 + d2b611f commit c3570c5
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 55 deletions.
1 change: 1 addition & 0 deletions ipinfo/cache/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"""

import cachetools

from .interface import CacheInterface


Expand Down
3 changes: 2 additions & 1 deletion ipinfo/details.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Details returned by the IPinfo service.
"""


class Details:
"""Encapsulates data for single IP address."""

Expand All @@ -14,7 +15,7 @@ def __getattr__(self, attr):
if attr in self.details:
return self.details[attr]
else:
raise AttributeError('{} is not a valid attribute of Details'.format(attr))
raise AttributeError("{} is not a valid attribute of Details".format(attr))

@property
def all(self):
Expand Down
2 changes: 2 additions & 0 deletions ipinfo/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Exceptions thrown by the IPinfo service.
"""


class RequestQuotaExceededError(Exception):
"""Error indicating that users monthly request quota has been passed."""

pass
54 changes: 32 additions & 22 deletions ipinfo/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
import ipaddress
import json
import os
import requests
import sys

import requests

from .cache.default import DefaultCache
from .details import Details
from .exceptions import RequestQuotaExceededError
Expand All @@ -18,45 +20,49 @@ class Handler:
and maintains access to cache.
"""

API_URL = 'https://ipinfo.io'
API_URL = "https://ipinfo.io"
CACHE_MAXSIZE = 4096
CACHE_TTL = 60 * 60 * 24
COUNTRY_FILE_DEFAULT = 'countries.json'
COUNTRY_FILE_DEFAULT = "countries.json"
REQUEST_TIMEOUT_DEFAULT = 2

def __init__(self, access_token=None, **kwargs):
"""Initialize the Handler object with country name list and the cache initialized."""
self.access_token = access_token
self.countries = self._read_country_names(kwargs.get('countries_file'))
self.countries = self._read_country_names(kwargs.get("countries_file"))

self.request_options = kwargs.get('request_options', {})
if 'timeout' not in self.request_options:
self.request_options['timeout'] = self.REQUEST_TIMEOUT_DEFAULT
self.request_options = kwargs.get("request_options", {})
if "timeout" not in self.request_options:
self.request_options["timeout"] = self.REQUEST_TIMEOUT_DEFAULT

if 'cache' in kwargs:
self.cache = kwargs['cache']
if "cache" in kwargs:
self.cache = kwargs["cache"]
else:
cache_options = kwargs.get('cache_options', {})
maxsize = cache_options.get('maxsize', self.CACHE_MAXSIZE)
ttl = cache_options.get('ttl', self.CACHE_TTL)
cache_options = kwargs.get("cache_options", {})
maxsize = cache_options.get("maxsize", self.CACHE_MAXSIZE)
ttl = cache_options.get("ttl", self.CACHE_TTL)
self.cache = DefaultCache(maxsize, ttl, **cache_options)

def getDetails(self, ip_address=None):
"""Get details for specified IP address as a Details object."""
raw_details = self._requestDetails(ip_address)
raw_details['country_name'] = self.countries.get(raw_details.get('country'))
raw_details['ip_address'] = ipaddress.ip_address(raw_details.get('ip'))
raw_details['latitude'], raw_details['longitude'] = self._read_coords(raw_details.get('loc'))
raw_details["country_name"] = self.countries.get(raw_details.get("country"))
raw_details["ip_address"] = ipaddress.ip_address(raw_details.get("ip"))
raw_details["latitude"], raw_details["longitude"] = self._read_coords(
raw_details.get("loc")
)
return Details(raw_details)

def _requestDetails(self, ip_address=None):
"""Get IP address data by sending request to IPinfo API."""
if ip_address not in self.cache:
url = self.API_URL
if ip_address:
url += '/' + ip_address
url += "/" + ip_address

response = requests.get(url, headers=self._get_headers(), **self.request_options)
response = requests.get(
url, headers=self._get_headers(), **self.request_options
)
if response.status_code == 429:
raise RequestQuotaExceededError()
response.raise_for_status()
Expand All @@ -67,26 +73,30 @@ def _requestDetails(self, ip_address=None):
def _get_headers(self):
"""Built headers for request to IPinfo API."""
headers = {
'user-agent': 'IPinfoClient/Python{version}/1.0'.format(version=sys.version_info[0]),
'accept': 'application/json'
"user-agent": "IPinfoClient/Python{version}/1.0".format(
version=sys.version_info[0]
),
"accept": "application/json",
}

if self.access_token:
headers['authorization'] = 'Bearer {}'.format(self.access_token)
headers["authorization"] = "Bearer {}".format(self.access_token)

return headers

def _read_coords(self, location):
lat, lon = None, None
coords = tuple(location.split(',')) if location else ''
coords = tuple(location.split(",")) if location else ""
if len(coords) == 2 and coords[0] and coords[1]:
lat, lon = coords[0], coords[1]
return lat, lon

def _read_country_names(self, countries_file=None):
"""Read list of countries from specified country file or default file."""
if not countries_file:
countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT)
countries_file = os.path.join(
os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT
)
with open(countries_file) as f:
countries_json = f.read()

Expand Down
13 changes: 7 additions & 6 deletions requirements.in
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
cachetools==2.1.0
pip-tools==3.1.0
pycodestyle==2.4.0
pytest==3.8.2
python-dateutil==2.6.1
pytz==2017.2
# For app
requests>=2.18.4
cachetools==3.1.1
pytest==4.5.0

# For dev
pip-tools==3.7.0
black==19.3b0
21 changes: 11 additions & 10 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@
# This file is autogenerated by pip-compile
# To update, run:
#
# pip-compile --no-index --output-file requirements.txt requirements.in
# pip-compile --no-index --output-file=requirements.txt requirements.in
#
appdirs==1.4.3 # via black
atomicwrites==1.3.0 # via pytest
attrs==19.1.0 # via pytest
cachetools==2.1.0
attrs==19.1.0 # via black, pytest
black==19.3b0
cachetools==3.1.1
certifi==2019.3.9 # via requests
chardet==3.0.4 # via requests
click==7.0 # via pip-tools
click==7.0 # via black, pip-tools
idna==2.8 # via requests
more-itertools==6.0.0 # via pytest
pip-tools==3.1.0
pip-tools==3.7.0
pluggy==0.9.0 # via pytest
py==1.8.0 # via pytest
pycodestyle==2.4.0
pytest==3.8.2
python-dateutil==2.6.1
pytz==2017.2
pytest==4.5.0
requests==2.21.0
six==1.12.0 # via pip-tools, pytest, python-dateutil
six==1.12.0 # via pip-tools, pytest
toml==0.10.0 # via black
urllib3==1.24.1 # via requests
wcwidth==0.1.7 # via pytest
29 changes: 14 additions & 15 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,17 @@
You can visit our developer docs at https://ipinfo.io/developers.
"""

setup(name='ipinfo',
version='1.1.1',
description='Official Python library for IPInfo',
long_description=long_description,
url='https://github.com/ipinfo/python',
author='James Timmins',
author_email='[email protected]',
license='Apache License 2.0',
packages=['ipinfo', 'ipinfo.cache'],
install_requires=[
'requests',
'cachetools',
],
include_package_data=True,
zip_safe=False)
setup(
name="ipinfo",
version="1.1.2",
description="Official Python library for IPInfo",
long_description=long_description,
url="https://github.com/ipinfo/python",
author="James Timmins",
author_email="[email protected]",
license="Apache License 2.0",
packages=["ipinfo", "ipinfo.cache"],
install_requires=["requests", "cachetools", "six"],
include_package_data=True,
zip_safe=False,
)
1 change: 1 addition & 0 deletions tests/details_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest

from ipinfo.details import Details


Expand Down
3 changes: 2 additions & 1 deletion tests/handler_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import ipaddress

from ipinfo.cache.default import DefaultCache
from ipinfo.details import Details
from ipinfo.handler import Handler
import ipaddress


def test_init():
Expand Down

0 comments on commit c3570c5

Please sign in to comment.