def lookup_postcode_v2(postcode, base=None): """call external service with @param: NL postcode , receive a dict with keys success (False, True). if not success: the key 'error' is added (dict with keys code and errormessage) otherwise a key 'resources' (list of dicts streets, city or an empty list if not found) Note: a NL postcode can have more (two) streets Author: Nico de Groot PoF""" import urllib2 import socket import json key = "get you're key from apiwise.nl' base = base or "https://postcode-api.apiwise.nl/v2/addresses/?postcode=" headers = {} headers['X-Api-Key'] = key url = base + postcode.replace(" ", "") # P6 format socket.setdefaulttimeout(6) req = urllib2.Request(url, None, headers) try: result = json.loads(urllib2.urlopen(req).read()) except urllib2.URLError, e: return dict(success = False, error=dict(code = 0, message = 'URL problem with %s: %s'%(url,e.reason))) except urllib2.HTTPError, e: return dict(success = False, error=dict(code = e.code, message = 'HTTPError on %s: %s'%(url,e.reason))) except socket.timeout, e: return dict(success = False, error=dict(code = 0, message = 'External service timeout')) else: streets = [] for address in result['_embedded']['addresses']: street_city = dict(street=address["street"], city=address["city"]["label"]) if street_city not in streets: streets.append(street_city) return dict(success=True, resources=streets) def main(): print lookup_postcode_v2('1234 AB')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question