/google_app/utils.py

https://code.google.com/p/dwarftherapist/ · Python · 55 lines · 51 code · 3 blank · 1 comment · 4 complexity · 376b6406c8ca32cf71060d04d84e4b3d MD5 · raw file

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