Coverage for jutil/request.py : 48%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import logging
2from typing import Tuple
3from django.conf import settings
4import requests
5import socket
8logger = logging.getLogger(__name__)
11def get_geo_ip(ip: str, exceptions: bool = False, timeout: int = 10) -> dict:
12 """
13 Returns geo IP info or empty dict if geoip query fails at http://ipstack.com.
14 requires settings.IPSTACK_TOKEN set as valid access token to the API.
16 Example replies:
18 {'country_name': 'United States', 'country_code': 'US', 'region_code': 'TX', 'region_name': 'Texas',
19 'ip': '76.184.236.184', 'latitude': 33.1507, 'time_zone': 'America/Chicago', 'metro_code': 623, 'city':
20 'Frisco', 'longitude': -96.8236, 'zip_code': '75033'}
22 {'latitude': 60.1641, 'country_name': 'Finland', 'zip_code': '02920', 'region_name': 'Uusimaa', 'city':
23 'Espoo', 'metro_code': 0, 'ip': '194.100.27.41', 'time_zone': 'Europe/Helsinki', 'country_code': 'FI',
24 'longitude': 24.7136, 'region_code': '18'}
26 :param ip: str
27 :param exceptions: if True raises Exception on failure
28 :param timeout: timeout in seconds
29 :return: dict
30 """
31 try:
32 res = requests.get('http://api.ipstack.com/{}?access_key={}&format=1'.format(ip, settings.IPSTACK_TOKEN), timeout=timeout)
33 if res.status_code != 200: 33 ↛ 34line 33 didn't jump to line 34, because the condition on line 33 was never true
34 if exceptions:
35 raise Exception('api.ipstack.com HTTP {}'.format(res.status_code))
36 return {}
37 return res.json()
38 except Exception as e:
39 msg = 'geoip({}) failed: {}'.format(ip, e)
40 logger.error(msg)
41 if exceptions:
42 raise
43 return {}
46def get_ip_info(ip: str, exceptions: bool = False, timeout: int = 10) -> Tuple[str, str, str]:
47 """
48 Returns (ip, country_code, host) tuple of the IP address.
49 :param ip: IP address
50 :param exceptions: Raise Exception or not
51 :param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host name.
52 :return: (ip, country_code, host)
53 """
54 if not ip: # localhost 54 ↛ 55line 54 didn't jump to line 55, because the condition on line 54 was never true
55 return '', '', ''
56 host = ''
57 country_code = get_geo_ip(ip, exceptions=exceptions, timeout=timeout).get('country_code', '')
58 try:
59 res = socket.gethostbyaddr(ip)
60 host = res[0][:255] if ip else ''
61 except Exception as e:
62 msg = 'socket.gethostbyaddr({}) failed: {}'.format(ip, e)
63 logger.error(msg)
64 if exceptions:
65 raise e
66 return ip, country_code, host