22import httplib
33import simplejson
44import sys
5+
56from urllib import urlencode
7+ from xml .etree import ElementTree
68
79class GeoNames ():
810"""
@@ -29,10 +31,50 @@ def _api_call(self, method, resource, **kwargs):
2931return response .read ()
3032
3133def get_connection (self ):
34+ """
35+ Return a connection object to the webservice.
36+ """
3237c = httplib .HTTPConnection (self .server )
3338return c
39+
40+ def search (self , name , country ):
41+ """
42+ Perform a search for a country's information.
43+ """
44+ # we only want exact matches, and we only want one possible match.
45+ xml = self ._api_call ('GET' , 'search' , name_equals = name , country = country , maxRows = 1 )
46+ root_element = ElementTree .XML (xml )
47+ results = root_element .find ('totalResultsCount' ).text
48+ if not results :
49+ raise GeoNameResultException ("No results returned for query." )
50+ return GeoResult (
51+ name = root_element .find ('geoname/name' ).text ,
52+ country_name = root_element .find ('geoname/countryName' ).text ,
53+ country_code = root_element .find ('geoname/countryCode' ).text ,
54+ latitude = root_element .find ('geoname/lat' ).text ,
55+ longitude = root_element .find ('geoname/lng' ).text ,
56+ )
57+
3458
35-
59+ class GeoResult (object ):
60+ """
61+ Result object stores data returned from GeoNames api accessor object.
62+ """
63+ def __init__ (self , name = None , country_name = None , country_code = None , latitude = None , longitude = None ):
64+ self .name = name
65+ self .country_name = country_name
66+ self .country_code = country_code
67+ self .latitude = latitude
68+ self .longitude = longitude
69+
70+ def is_complete (self ):
71+ complete = True
72+ for key , val in self .__dict__ .items ():
73+ if not val :
74+ complete = False
75+ break
76+ return complete
77+
3678
3779class GeoNameException (Exception ):
3880"""
@@ -41,4 +83,10 @@ class GeoNameException(Exception):
4183def __init__ (self , value ):
4284self .message = value
4385def __str__ (self ):
44- return repr (self .message )
86+ return repr (self .message )
87+
88+ class GeoNameResultException (GeoNameException ):
89+ """
90+ Error getting results from GeoName webservice.
91+ """
92+ pass
0 commit comments