Last active
September 11, 2017 11:30
-
-
Save jaklinger/f273d68f439c2fc2bdbe8c3e10523ed7 to your computer and use it in GitHub Desktop.
Snippet giving an example of how to query the Google Maps API, with proxy information.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
import time | |
'''Decorator for retrying up to 10 times''' | |
def retry(exception): | |
def outer_retry(f): | |
def inner_retry(*args,attempt=0): | |
n=0 | |
while True: | |
try: | |
return f(*args,attempt=n) | |
except exception as err: | |
n += 1 | |
time.sleep(10) | |
if n == 10: | |
raise err | |
print("Retrying...") | |
return inner_retry | |
return outer_retry | |
'''Ask Google Maps for normalised results for the query `address`''' | |
@retry(IndexError) # Retry after IndexError | |
def google_map_query(address,attempt): # Note: attempt is for your book-keeping | |
# Make the request and check for success | |
r = requests.get("https://maps.googleapis.com/maps/api/geocode/json", | |
params=dict(key="<YOUR_API_KEY>",address=address), | |
# Comment out the following lines if you don't use a proxy | |
proxies=dict(https="https://<YOUR_NAME>:<YOUR_PASSWORD>@<PROXY_SERVER>:<PORT>"), | |
verify=False) | |
r.raise_for_status() | |
# Load the json and return the result | |
js = json.loads(r.text) | |
if len(js["results"]) == 0: | |
return None | |
return js["results"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment