def dispatch_request(self): if request.remote_addr == '127.0.0.1': lat = -25.43555700 lng = -49.27032780 else: location = freegeoip(request.remote_addr).json lat = location['lat'] lng = location['lng'] if g.user: stmt = text( "SELECT * FROM tour_points WHERE acos(sin(:lat) * sin(latitude) + cos(:lat) * cos(latitude) * cos(longitude - (:lng))) * 6371 <= 5 AND public IS TRUE" ) nearby = engine.execute(stmt, {'lat': lat, 'lng': lng}) return render_template('index.html', app_id=FACEBOOK_API['APP_ID'], app_name=FACEBOOK_API['APP_NAME'], user=g.user, nearby=nearby) stmt = text( "SELECT * FROM tour_points WHERE acos(sin(:lat) * sin(latitude) + cos(:lat) * cos(latitude) * cos(longitude - (:lng))) * 6371 <= 5 AND public IS TRUE AND category = 'restaurant'" ) nearby = engine.execute(stmt, {'lat': lat, 'lng': lng}) return render_template('login.html', app_id=FACEBOOK_API['APP_ID'], app_name=FACEBOOK_API['APP_NAME'], nearby=nearby)
def index(): print 'the static folder: ' + app.static_folder print 'the static url_path: ' + app.static_url_path print 'template folder: ' + app.template_folder # get user address. assign my public NAT ip if in debug mode # not using request.remote_addr because of potential proxy issues (incorrect remote ip) user_address= request.environ['REMOTE_ADDR'] if not app.debug else debug_config.get('user_address') print 'the REMOTE_ADDR address is %s ' % user_address geolocation = geocoder.freegeoip(user_address).parse print 'the country is %(country)s' % geolocation print 'the city is %(city)s' % geolocation # with codecs.open(file_path, 'r', encoding='utf-8') as fp: # response = fp.read() # no jinja2 (client side render - knockoutjs) #homepage = 'html/restaurants.html' #return app.send_static_file(homepage) # jinja2 render (server side render + knockoutjs for handlers) homepage = 'restaurants.html' return render_template(homepage, restaurants = database.query_all(Restaurant), **geolocation)
def index(): print 'the static folder: ' + app.static_folder print 'the static url_path: ' + app.static_url_path print 'template folder: ' + app.template_folder # get user address. assign my public NAT ip if in debug mode # not using request.remote_addr because of potential proxy issues (incorrect remote ip) user_address = request.environ[ 'REMOTE_ADDR'] if not app.debug else debug_config.get('user_address') print 'the REMOTE_ADDR address is %s ' % user_address geolocation = geocoder.freegeoip(user_address).parse print 'the country is %(country)s' % geolocation print 'the city is %(city)s' % geolocation # with codecs.open(file_path, 'r', encoding='utf-8') as fp: # response = fp.read() # no jinja2 (client side render - knockoutjs) #homepage = 'html/restaurants.html' #return app.send_static_file(homepage) # jinja2 render (server side render + knockoutjs for handlers) homepage = 'restaurants.html' return render_template(homepage, restaurants=database.query_all(Restaurant), **geolocation)
def __init__(self): # forecast.io api key: f = open('/home/christoph/.config/forecast-io-key') key = f.readline().rstrip() f.close() # Get current longitude and latitude based on IP address: ip = requests.get('http://ipinfo.io/ip').text.rstrip() loc = geocoder.freegeoip(ip) self.city = loc.locality if self.city == None: self.city = geocoder.google([loc.lat, loc.lng], \ method='reverse').city # Get weather info: root_url = 'https://api.forecast.io/forecast/' weather = requests.get(root_url + key + '/' + str(loc.lat) + ',' + \ str(loc.lng)) weather = json.loads(weather.text) # Convert temperature to Celcius: self.temperature = round((weather['currently']['temperature']-32) * 5/9) # Get current weather condition: condition = weather['currently']['summary'] # Translate city when approriate: cdict = dict({'Boston': {'ga': 'Bostún'}, 'Dublin': {'ga': 'Baile Átha Cliath'}}) language = locale.getlocale()[0] if language == 'ga_IE': try: self.city = cdict[self.city]['ga'] except KeyError: self.city = self.city elif language == 'de_DE': try: self.city = cdict[self.city]['de'] except KeyError: self.city = self.city # Get weather translation and icon: df = pd.read_csv(os.path.expanduser('~/') + '.i3/scripts/weather.csv') df = df[df.en == condition] if df.shape[0] == 0: self.icon = '' self.web_icon = '' self.weather = condition else: self.icon = df.icon.values[0] self.web_icon = df.web_icon.values[0] self.icon = bytes(self.icon, 'ascii').decode('unicode-escape') if language == 'de_DE': self.weather = df.de.values[0] elif language == 'ga_IE': self.weather = df.ga.values[0] else: self.weather = condition
def get_users_location(request): x_forwarded = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded: ip = x_forwarded.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') ip = '78.141.101.59' gi = geocoder.freegeoip(ip) return gi.json
def geocode(self, obj): """ Proccess an IP with the FreeGeoIP API. :param obj: A dict-like object containing a key that returns an IP address to be geocoded. :return: dict """ ip = obj[self.col_name] logger.info("Geocoding IP address: {0}".format(ip)) geocode = geocoder.freegeoip(ip) return geocode.json
def add_client(self, username, key): app = self.keyhandle(key) from uuid import getnode as get_mac import platform import sys import geocoder from requests import get mac = get_mac() sel = ("SELECT * FROM clients WHERE ID='" + str(mac) + "'") cursor = cnx.cursor() cursor.execute(sel) x = 0 for item in cursor: x = x + 1 if x == 0: IP = get('https://api.ipify.org').text Location = geocoder.freegeoip(str(IP)) try: Location = Location.city + ", " + Location.country except: print("[ BACKEND ] : Unable to get location!") print("[ BACKEND ] : Setting location as: Unknown") Location = "Unknown" #print(Location) upld = ("INSERT INTO clients " "(Name, Location, OS, ID)" "VALUES (%(Name)s, %(Location)s, %(OS)s, %(ID)s)") upld_dat = { 'Name': platform.uname()[1], 'Location': Location, 'OS': platform.platform(), 'ID': mac } cursor = cnx.cursor() cursor.execute(upld, upld_dat) cnx.commit() cursor.close() self.log( app, " Added client to tracking database with the ID: " + str(mac)) else: self.log( app, " Ignoring request to add an existing client to the tracking database with ID: " + str(mac))
def test_freegeoip(): g = geocoder.freegeoip(ip) assert g.ok
#!/usr/bin/python # an IP/Hostname locating script import os import sys try: import geocoder except: print 'Geocoder is required ... pip install geocoder' the_IP = raw_input("[+] IP address/Hostname: ") loc = geocoder.freegeoip(the_IP) print "-" * 30 print "\n[+] Locating %s \n" % the_IP print "-" * 30 print "[+]", loc.json print "-" * 30 print "[+] Complete\n"
def crawl_geo_data(self, provider: str = 'arcgis') -> dict: """ Crawl continuous geo data based on categorical geo data :param provider: str Name of the provider to use: -> arcgis: ArcGis -> google: Google Maps :return: Dictionary containing the results of the geo-coding """ _geo: dict = {} _status: str = '' for i, loc in enumerate(self.location): #while _status.find('REQUEST_DENIED') >= 0 or _status == '': if provider == 'arcgis': _g: geocoder = geocoder.arcgis(location=loc, maxRows=1, method='geocode') elif provider == 'google': _g: geocoder = geocoder.google(location=loc, maxRows=1, method='geocode') elif provider == 'bing': _g: geocoder = geocoder.bing(location=loc, maxRows=1, method='geocode') elif provider == 'baidu': _g: geocoder = geocoder.baidu(location=loc, maxRows=1, method='geocode') elif provider == 'freegeoip': _g: geocoder = geocoder.freegeoip(location=loc, maxRows=1, method='geocode') elif provider == 'osm': _g: geocoder = geocoder.osm(location=loc, maxRows=1, method='geocode') elif provider == 'tomtom': _g: geocoder = geocoder.tomtom(location=loc, maxRows=1, method='geocode') elif provider == 'yahoo': _g: geocoder = geocoder.yahoo(location=loc, maxRows=1, method='geocode') else: raise HappyLearningUtilsException( 'Provider "{}" for geocoding not supported'.format( provider)) _status = _g.status if _status.find('OK') >= 0: _geo.update({loc: _g.json}) elif _status.find('ERROR') >= 0: _geo.update({loc: 'NaN'}) else: if _status.find('REQUEST_DENIED') < 0: raise HappyLearningUtilsException( 'Unknown request error "{}"'.format(_g.status)) if self.full_path is not None: DataExporter(obj=_geo, file_path=self.full_path).file() return _geo
dataf # In[19]: z # In[ ]: import geocoder g = geocoder.freegeoip('99.240.181.199') g.json # In[ ]: l # In[49]: cf.go_offline()
#SO code ends here def simpVector(origin, dest): return [dest[0]-origin[0], dest[1]-origin[1]] inFile = r'/data/working/access2.master.log.json' inData = json.loads(open(inFile,'r').read()) #grab your own IP address resp = urllib2.urlopen('http://bot.whatismyipaddress.com/') localIP = resp.read() print localIP g = geocoder.freegeoip(localIP) localX = g.json['lng'] localY = g.json['lat'] originPnt = [localX, localY] #Now you're ready to graph loopEnd = 500000 loopCount = 0 filter = 0 #programatically determine max count, later... maxCount = 200 #colorPlot{"200":'g',}
# import requests # # def get_lat_long(): # r = requests.get(url='http://ipinfo.io/json') # data = r.json() # return data['loc'] # # import os # import platform # # print(platform.system()) import geocoder import geocoder g = geocoder.freegeoip('192.168.10.70') g.latlng g.city
def geocode3(address): g = geocoder.freegeoip(address) latlng = g.latlng return latlng
def test_freegeoip(): g = geocoder.freegeoip(location) assert g.ok osm_count, fields_count = g.debug()[0] assert osm_count >= 3 assert fields_count >= 12
import geocoder import json import locale import os import requests import pandas as pd import urllib # forecast.io api key: f = open('/home/christoph/.config/forecast-io-key') key = f.readline().rstrip() f.close() # Get current longitude and latitude based on IP address: ip = requests.get('http://ipinfo.io/ip').text.rstrip() loc = geocoder.freegeoip(ip) city = loc.locality if city == None: city = geocoder.google([loc.lat, loc.lng], method='reverse').city # Get weather info: root_url = 'https://api.forecast.io/forecast/' weather = requests.get(root_url + key + '/' + str(loc.lat) + ',' + str(loc.lng)) weather = json.loads(weather.text) # Convert temperature to Celcius: temperature = round((weather['currently']['temperature'] - 32) * 5/9) # Get current weather condition: condition = weather['currently']['summary']
ipSet.add(re.findall(rePat, fle)[0]) apachewalk = os.walk(r'/data/raw/apachelogs') print 'walking apache logs' for root, subs, files in apachewalk: for fle in files: ipSet.add(re.findall(rePat, fle)[0]) print "number of IPs to geolocate:", len(ipSet) outjson = r'/data/reference/geo/geoip.json' geoDict = {} print "geocoding IP addresses" loopCount = 0 for ip in ipSet: loopCount = loopCount + 1 if loopCount % 20 == 0: print loopCount, "records geocoded..." g = geocoder.freegeoip(ip) geoDict[ip] = g.json #break print "wriiting out file" lclFile = open(outjson, 'w') lclFile.write(json.dumps(geoDict, indent=4, sort_keys=True)) lclFile.close() print "Done!"