Skip to content

Commit 677a5f2

Browse files
Added api calls and search processing.
1 parent 8af8da8 commit 677a5f2

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

‎geonames.py‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
importhttplib
33
importsimplejson
44
importsys
5+
56
fromurllibimporturlencode
7+
fromxml.etreeimportElementTree
68

79
classGeoNames():
810
"""
@@ -29,10 +31,50 @@ def _api_call(self, method, resource, **kwargs):
2931
returnresponse.read()
3032

3133
defget_connection(self):
34+
"""
35+
Return a connection object to the webservice.
36+
"""
3237
c=httplib.HTTPConnection(self.server)
3338
returnc
39+
40+
defsearch(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+
ifnotresults:
49+
raiseGeoNameResultException("No results returned for query.")
50+
returnGeoResult(
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+
classGeoResult(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+
defis_complete(self):
71+
complete=True
72+
forkey, valinself.__dict__.items():
73+
ifnotval:
74+
complete=False
75+
break
76+
returncomplete
77+
3678

3779
classGeoNameException(Exception):
3880
"""
@@ -41,4 +83,10 @@ class GeoNameException(Exception):
4183
def__init__(self, value):
4284
self.message=value
4385
def__str__(self):
44-
returnrepr(self.message)
86+
returnrepr(self.message)
87+
88+
classGeoNameResultException(GeoNameException):
89+
"""
90+
Error getting results from GeoName webservice.
91+
"""
92+
pass

0 commit comments

Comments
(0)