PageRenderTime 55ms CodeModel.GetById 47ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/google_app/utils.py

https://code.google.com/p/dwarftherapist/
Python | 55 lines | 52 code | 2 blank | 1 comment | 1 complexity | 376b6406c8ca32cf71060d04d84e4b3d MD5 | raw file
 1import logging
 2import urllib
 3from xml.etree import ElementTree as ET
 4from pprint import pformat
 5
 6xml_to_dict_map = {
 7    'CountryCode': 'country',
 8    'RegionName': 'region_name',
 9    'RegionCode': 'region_code',
10    'City': 'city'
11}
12
13def ip_info(ip):
14    """
15<?xml version="1.0" encoding="UTF-8"?>
16<Response>
17        <Ip>1.2.3.4</Ip>
18        <Status>OK</Status>
19        <CountryCode>US</CountryCode>
20        <CountryName>United States</CountryName>
21        <RegionCode>22</RegionCode>
22        <RegionName>Arkansas</RegionName>
23        <City>Some City</City>
24        <ZipPostalCode>12345</ZipPostalCode>
25        <Latitude>40.0000</Latitude>
26        <Longitude>-120.000</Longitude>
27        <Gmtoffset>-5.0</Gmtoffset>
28        <Dstoffset>-4.0</Dstoffset>
29</Response>
30    """
31    info = {
32        'country': 'unknown',
33        'region_code': 'unknown',
34        'region_name': 'unknown',
35        'city': 'unknown',
36        'ip': ip
37    }
38    try:
39        gs = urllib.urlopen('http://blogama.org/ip_query.php?ip=%s&output=xml' % ip)
40        txt = gs.read()
41    except:
42        logging.error('GeoIP servers not available')
43        return info
44    
45    try:
46        tree = ET.fromstring(txt.strip())
47        for xml_val, dict_key in xml_to_dict_map.items():
48            elem = tree.find(xml_val)
49            if elem is not None:
50                info[dict_key] = elem.text
51    except:
52        logging.error("error parsing IP result %s", txt)
53    logging.info("got info for %s", ip)
54    logging.info(pformat(info))
55    return info