forked from steffex/pyPostcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
188 lines (146 loc) · 4.82 KB
/
Copy path__init__.py
File metadata and controls
188 lines (146 loc) · 4.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
pyPostcode by Stefan Jansen
pyPostcode is an api wrapper for http://postcodeapi.nu
'''
import httplib
import json
import logging
__version__ = '0.3'
class pyPostcodeException(Exception):
def __init__(self, id, message):
self.id = id
self.message = message
class Api(object):
def __init__(self, api_key, api_version=(2, 0, 0)):
if api_key is None or api_key is '':
raise pyPostcodeException(
0, "Please request an api key on http://postcodeapi.nu")
self.api_key = api_key
self.api_version = api_version
if api_version >= (2, 0, 0):
self.url = 'postcode-api.apiwise.nl'
else:
self.url = 'api.postcodeapi.nu'
def handleresponseerror(self, status):
if status == 401:
msg = "Access denied! Api-key missing or invalid"
elif status == 404:
msg = "No result found"
elif status == 500:
msg = "Unknown API error"
else:
msg = "dafuq?"
raise pyPostcodeException(status, msg)
def request(self, path=None):
'''Helper function for HTTP GET requests to the API'''
headers = {
"Accept": "application/json",
"Accept-Language": "en",
# this is the v1 api
"Api-Key": self.api_key,
# this is the v2 api
"X-Api-Key": self.api_key,
}
if self.api_version >= (2, 0, 0):
conn = httplib.HTTPSConnection(self.url)
else:
conn = httplib.HTTPConnection(self.url)
'''Only GET is supported by the API at this time'''
conn.request('GET', path, None, headers)
result = conn.getresponse()
if result.status is not 200:
conn.close()
self.handleresponseerror(result.status)
resultdata = result.read()
conn.close()
jsondata = json.loads(resultdata)
if self.api_version >= (2, 0, 0):
data = jsondata.get('_embedded', {}).get('addresses', [])
if data:
data = data[0]
else:
data = None
else:
data = jsondata['resource']
return data
def getaddress(self, postcode, house_number=None):
if house_number is None:
house_number = ''
if self.api_version >= (2, 0, 0):
path = '/v2/addresses/?postcode={0}&number={1}'
else:
path = '/{0}/{1}'
path = path.format(
str(postcode),
str(house_number))
try:
data = self.request(path)
except pyPostcodeException as e:
logging.error(
'Error looking up %s%s%s on %s: %d %s',
postcode, house_number and ' ' or '', house_number, self.url,
e.id, e.message)
data = None
except Exception as e:
logging.exception(e)
data = None
if data is not None:
return Resource(data)
else:
return False
class Resource(object):
def __init__(self, data):
self._data = data
@property
def street(self):
return self._data['street']
@property
def house_number(self):
'''
House number can be empty when postcode search
is used without house number
'''
return self._data.get('number', self._data.get('house_number'))
@property
def postcode(self):
return self._data.get('postcode')
@property
def town(self):
return self._data.get('city', {}).get('label', self._data.get('town'))
@property
def municipality(self):
result = self._data.get('municipality', {})
if isinstance(result, dict):
result = result.get('label')
return result
@property
def province(self):
result = self._data.get('province', {})
if isinstance(result, dict):
result = result.get('label')
return result
def _get_geo_coordinates(self, geo_type):
return self._data.get('geo', {}).get('center', {}).get(geo_type)\
.get('coordinates', [None, None])
@property
def latitude(self):
if self._data.get('latitude'):
return self._data.get('latitude')
return self._get_geo_coordinates('wgs84')[0]
@property
def longitude(self):
if self._data.get('longitude'):
return self._data.get('longitude')
return self._get_geo_coordinates('wgs84')[1]
@property
def x(self):
if self._data.get('x'):
return self._data.get('x')
return self._get_geo_coordinates('rd')[0]
@property
def y(self):
if self._data.get('y'):
return self._data.get('y')
return self._get_geo_coordinates('rd')[1]