Created
February 13, 2017 04:39
-
-
Save phoenisx/3758dfb053c3d97f4f7bc65d6e15d39d to your computer and use it in GitHub Desktop.
A Simple Pinging API, to make calls to Google Geolocation API per second
This file contains 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
#!/usr/bin/python | |
############################################################################################### | |
# | |
# Basic Pinging API, to make calls to Google Geolocation API per second | |
# Uses Ratelimiting, for limiting the calls to one second only... | |
# | |
# * This app, uses a `.json` file [calls.json], for getting Lat/Lons, that needs to be | |
# reversegeocoded using the Google API... | |
# * Uses Formatter, to format String, as required... | |
# * I don't remember, but I required ascii convertion of json data (which is by default | |
# unicode) | |
# | |
############################################################################################### | |
import urllib, json, string | |
from pprint import pprint | |
# Download this library before using this Sample Code... | |
from ratelimit import * | |
class PartialFormatter(string.Formatter): | |
def __init__(self, missing='~~', bad_fmt='!!'): | |
self.missing, self.bad_fmt=missing, bad_fmt | |
def get_field(self, field_name, args, kwargs): | |
# Handle a key not found | |
try: | |
val=super(PartialFormatter, self).get_field(field_name, args, kwargs) | |
# Python 3, 'super().get_field(field_name, args, kwargs)' works | |
except (KeyError, AttributeError): | |
val=None,field_name | |
return val | |
def format_field(self, value, spec): | |
# handle an invalid format | |
if value==None: return self.missing | |
try: | |
return super(PartialFormatter, self).format_field(value, spec) | |
except ValueError: | |
if self.bad_fmt is not None: return self.bad_fmt | |
else: raise | |
def ascii_encode_dict(data): | |
ascii_encode = lambda x: x if type(x) == float else x.encode('ascii') | |
return dict(map(ascii_encode, pair) for pair in data.items()) | |
rows = "" | |
with open('calls.json') as data_file: | |
rows = json.load(data_file) | |
latlon = [ascii_encode_dict(i) for i in rows['rows']]; | |
url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&sensor=false" | |
fmt = PartialFormatter() | |
@rate_limited(1) | |
def call_google(url): | |
response = urllib.urlopen(url) | |
data = json.loads(response.read()) | |
print data | |
for dat in latlon: | |
call_google(fmt.format(url, **dat)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Json File should have a following format: