def global_data(request): results = {} client_ip = get_client_ip(request) results['client_ip'] = client_ip g = GeoIP() results['current_lat'] = DEFAULT_LATITUDE results['current_lng'] = DEFAULT_LONGITUDE results['current_city'] = DEFAULT_CITY results['current_country'] = DEFAULT_COUNTRY results['current_country_code'] = DEFAULT_COUNTRY_CODE results['geo_data'] = None if g.city(client_ip) != None: geo_data = g.city(client_ip) results['current_lat'] = geo_data['latitude'] results['current_lng'] = geo_data['longitude'] results['current_city'] = geo_data['city'] results['current_country'] = geo_data['country_name'] results['current_country_code'] = geo_data['country_code'] results['geo_data'] = geo_data results['user_login'] = get_user_login_object(request) activate_message = activate_email_reminder_message(request,results['user_login']) if activate_message == None: data = { 'user_login':results['user_login'], 'site_name': capitalize_first_letter(SITE_NAME) } results["request_message"] = handle_request_get_message(request,data) results['is_activate_message'] = False else: results["request_message"] = activate_message results['is_activate_message'] = True results['stage'] = STAGE return results
def handle(self, *args, **options): if not test_geoip_files(): return try: from django.contrib.gis.geoip import GeoIP print '[ ok ] Imported GeoIP' except ImportError: print "[ FAIL ] Unable to import 'django.contrib.gis.geoip'" g = GeoIP() g.city('206.86.95.58') print '[ ok ] Successfully mapped IP address to geographical location'
def test02_bad_query(self): "Testing GeoIP query parameter checking." cntry_g = GeoIP(city='<foo>') # No city database available, these calls should fail. with self.assertRaises(GeoIPException): cntry_g.city('google.com') with self.assertRaises(GeoIPException): cntry_g.coords('yahoo.com') # Non-string query should raise TypeError with self.assertRaises(TypeError): cntry_g.country_code(17) with self.assertRaises(TypeError): cntry_g.country_name(GeoIP)
def start(request): tempdic = {} geo = GeoIP() try: if settings.DEPLOY: my_ip_dat = geo.city(request.META['HTTP_X_REAL_IP']) else: my_ip_dat = geo.city(request.META['REMOTE_ADDR']) except Exception, e: my_ip_dat = {} my_ip_dat['country_code'] = 'NA' my_ip_dat['region'] = 'NA' my_ip_dat['city'] = 'NA' print "start geoip error: " + str(e)
def form_valid(self, form): from django.contrib.gis.geoip import GeoIP g = GeoIP() ip = self.request.META.get('REMOTE_ADDR', None) city = 'Moscow' if ip and g.city(ip): city = g.city(ip)['city'] form.instance.city = city if form.instance.height and form.instance.weight and form.instance.waist_circumference: form.instance.mass_index = 12 # ЗДЕСЬ ФОРМУЛА return super(UserCreateView, self).form_valid(form)
def render(self, context, instance, placeholder): request = context['request'] WS_EVENTS_URL = get_context_variable(request, "WS_EVENTS_URL", "http://iisdev1/iappsint/p13ndemo/api/I2KTaxonomy/GetEventList3") g = GeoIP() # ip = context['request'].META.get('REMOTE_ADDR', None) ip = context['request'].META.get('HTTP_X_REAL_IP', None) if not ip: ip = '192.152.183.80' if ip: loc = g.city(ip) if loc: req_str = WS_EVENTS_URL req_str += '?latitude=' + str(loc['latitude']) + '&longitude=' + str(loc['longitude']) req_str += '&num=' + str(instance.number) + '&numKm=' + str(instance.radius) req_str += '&discipline=' for discipline in instance.disciplines.all(): req_str = req_str + discipline.eva_code + ':' req_str += '&eventtype=' for type in instance.types.all(): req_str = req_str + type.name + ',' headers = {'Accept': 'application/json'} try: r = requests.get(req_str, headers=headers) context.update({'events': r.json()}) except: pass else: loc = None context.update({'location': loc}) return context
def home(request): geoip = GeoIP() client_ip = get_client_ip(request) country_record = geoip.country(client_ip) if country_record: country = country_record['country_name'] else: country = 'Not defined' city_record = geoip.city(client_ip) if city_record: city = city_record['city'] else: city = 'Not defined' lat_lon_record = geoip.lat_lon(client_ip) if lat_lon_record: (lat, lon) = lat_lon_record else: (lat, lon) = (-1, -1) return { 'client_ip': client_ip, 'country': country, 'city': city, 'lat': lat, 'lon': lon, }
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') queries = [self.addr] if self._is_dns_available(self.fqdn): queries.append(self.fqdn) for query in queries: # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query)) self.assertEqual({'country_code': 'US', 'country_name': 'United States'}, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('USA', d['country_code3']) self.assertEqual('San Antonio', d['city']) self.assertEqual('TX', d['region']) self.assertEqual(210, d['area_code']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) lon, lat = (-98, 29) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 0) self.assertAlmostEqual(lat, tup[1], 0)
def handle(self, *args, **options): cur = connection.cursor() g = GeoIP() cur.execute("SELECT id, release_id, created, ip4addr FROM apps_download") for id, release_id, created, ip4addr in cur.fetchall(): release = Release.objects.get(id = release_id) app = release.app when = created.date() print '{0:5} {1:30} {2:15} {3:10} {4:15}'.format(id, app.fullname, release.version, str(when), ipaddr_long_to_str(ip4addr)), sys.stdout.flush() dl = Download.objects.create(release = release, when = when, ip4addr = ip4addr) dl.save() increment_count(ReleaseDownloadsByDate, release = release, when = when) increment_count(ReleaseDownloadsByDate, release = None, when = when) geoinfo = g.city(ipaddr_long_to_str(ip4addr)) if geoinfo: country_geoloc, _ = GeoLoc.objects.get_or_create(country = geoinfo['country_code'], region = '', city = '') increment_count(AppDownloadsByGeoLoc, app = app, geoloc = country_geoloc) increment_count(AppDownloadsByGeoLoc, app = None, geoloc = country_geoloc) if geoinfo.get('city'): city_geoloc, _ = GeoLoc.objects.get_or_create(country = geoinfo['country_code'], region = geoinfo['region'], city = geoinfo['city']) increment_count(AppDownloadsByGeoLoc, app = app, geoloc = city_geoloc) increment_count(AppDownloadsByGeoLoc, app = None, geoloc = city_geoloc) print
def get_geo(ip, unknown=_('Unknown')): geo_ip = GeoIP() info = geo_ip.city(ip) or dict() return "%s:%s" % ( info.get('country_name') or unknown, info.get('city') or unknown, )
def gotolink(request, bookmark_id): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] client_geo = g.city(client_ip) client_city = client_geo['city'] + ',' + client_geo['region'] try: b = Bookmark.objects.get(pk=bookmark_id) except Bookmark.DoesNotExist: raise Http404("Weird -- Bookmark does not exist") b.accessCount += 1 b.save() alist = b.accessinfo_set.filter(accessIP__contains=client_ip) if (len(alist) == 0): a = b.accessinfo_set.create(accessIP=client_ip, accessCount=1) a.save() elif (len(alist) == 1): a = alist[0] a.accessCount += 1 a.save() else: return Http404("Internal accounting error") return HttpResponseRedirect(b.url)
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query)) self.assertEqual({'country_code': 'US', 'country_name': 'United States'}, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('USA', d['country_code3']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) self.assertEqual(713, d['area_code']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) lon, lat = (-95.4010, 29.7079) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
def home(request): #we record the ip adress for our visit counter g = GeoIP() ip = request.META.get('REMOTE_ADDR', None);country="";city=""; print ip; if ip: if g.city(ip): city = g.city(ip)['city']; country=g.city(ip)['country_name']; if country==None or country=="": country="inconnu" if city==None or city=="": city="inconnu" visitor,info = Visitor.objects.get_or_create(ip=ip,city=city,country=country,defaults={'visitCounter': 0}); visitor.update(); return render_from_pageId(request,0)
def get_geo_info(request): """ Get GeoInfo - Relies on Django to raise exception on improper configuration """ geo_info = { 'fqdn_or_ip': '', 'city': '', 'continent_code': '', 'region': '', 'charset': 0, 'area_code': 0, 'longitude': 0.0, 'country_code3': '', 'latitude': 0.0, 'postal_code': None, 'dma_code': 0, 'country_code': '', 'country_name': '', } fqdn_or_ip = getattr(defaults, 'GEOIP_DEBUG_DOMAIN_OR_IP', get_ip_address(request)) if fqdn_or_ip: cache_method = getattr(defaults, 'GEOIP_CACHE_METHOD') geo = GeoIP(cache=cache_method) try: ginfo = geo.city(fqdn_or_ip) geo_info.update(ginfo) except: try: ginfo = geo.country(fqdn_or_ip) geo_info.update(ginfo) except: pass geo_info['fqdn_or_ip'] = fqdn_or_ip return geo_info
def test05_unicode_response(self): "Testing that GeoIP strings are properly encoded, see #16553." g = GeoIP() d = g.city("www.osnabrueck.de") self.assertEqual("Osnabrück", d["city"]) d = g.country("200.7.49.81") self.assertEqual("Curaçao", d["country_name"])
def get_geoip_info(ip_address): # These need to match the geoip fields in models.LiveExperimentSession. geoip_info = dict(city = None, country_name = None, country_code = None, country_code_alt = None, longitude = None, latitude = None) try: g = GeoIP() city_information = g.city(ip_address) for key in geoip_info: if key in city_information and city_information[key]: # if not None geoip_info[key] = city_information[key] except Exception as e: exception_type = e.__class__.__name__ logger.warning( 'Could not get GeoIP information. Exception %s. Msg %s.'\ % (exception_type, e.message)) return geoip_info
def render(self, context, instance, placeholder): g = GeoIP() # ip = context['request'].META.get('REMOTE_ADDR', None) ip = context['request'].META.get('HTTP_X_REAL_IP', None) if not ip: ip = '192.152.183.80' if ip: loc = g.city(ip) if loc: req_str = EVENT_PERSONALIZATION_SERVER req_str += '?latitude=' + str( loc['latitude']) + '&longitude=' + str(loc['longitude']) req_str += '&num=' + str(instance.number) + '&numKm=' + str( instance.radius) req_str += '&discipline=' for discipline in instance.disciplines.all(): req_str = req_str + discipline.eva_code + ':' req_str += '&eventtype=' for type in instance.types.all(): req_str = req_str + type.name + ',' headers = {'Accept': 'application/json'} try: r = requests.get(req_str, headers=headers) context.update({'events': r.json()}) except: pass else: loc = None context.update({'location': loc}) return context
def registration(request): if request.method == 'POST': user_name = (request.POST.get('user_name')).strip() last_name = (request.POST.get('last_name')).strip() email = (request.POST.get('email')).strip() password = hashlib.md5( (request.POST.get('password')).strip()).hexdigest() data = {'user_name': user_name, 'last_name': last_name, 'email': email} ip = request.META.get('REMOTE_ADDR', None) g = GeoIP() if ip != '127.0.0.1': city = g.city(ip)['city'] else: city = 'Hyderabad' check = Usersdata.objects.filter(email=email) if check.exists() == False: Usersdata.objects.create(user_name=user_name, last_name=last_name, email=email, password=password, location=city, created_datetime=datetime.now()) return HttpResponseRedirect("/") else: data = {'message': "user with same email already exists"} return render(request, "login/login.html", data) else: return render(request, "userinfo/registration.html", {})
def home_location(): g = GeoIP() ip = get_ip_address("wlp8s0") location = g.city(ip) if location is not None: location["charset"] = ip return location
def get_geo(ip, unknown=_('Unknown')): g = GeoIP() info = g.city(ip) or dict() return "%s:%s" % ( info.get('country_name') or unknown, info.get('city') or unknown, )
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual('US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual('United States', func(query)) self.assertEqual( { 'country_code': 'US', 'country_name': 'United States' }, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('USA', d['country_code3']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) self.assertEqual(713, d['area_code']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) lon, lat = (-95.4010, 29.7079) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
def logged_in(sender, request, **kwargs): UserLocation = apps.get_model('users', 'UserLocation') x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip_address = x_forwarded_for.split(',')[0] else: ip_address = request.META.get('REMOTE_ADDR') geoip = GeoIP() try: city = geoip.city(ip_address) user = kwargs.get('user') UserLocation.objects.create( user=user, ip_address=ip_address, country_code=city.get('country_code'), country_name=city.get('country_name'), city=city.get('city'), latitude=city.get('latitude'), longitude=city.get('longitude'), continent_code=city.get('continent_code') ) except Exception as e: logger.debug(e)
def test05_unicode_response(self): "Testing that GeoIP strings are properly encoded, see #16553." g = GeoIP() d = g.city("www.osnabrueck.de") self.assertEqual('Osnabrück', d['city']) d = g.country('200.7.49.81') self.assertEqual('Curaçao', d['country_name'])
def index(request, selected_provider_id=sorted(connector.config.keys())[0]): ''' Handler for the accounts ''' sections = misc.getSiteSections(current_section) selected_provider_id = int(selected_provider_id) g = GeoIP() notsupported = 0; peers = connector.getPeerInfo(selected_provider_id) if 'error' in peers : peers = {} notsupported = 1 else : for peer in peers: info = g.city(peer['addr'].partition(':')[0]) if info is None: info = {} peer['ip'] = peer['addr'].partition(':')[0] peer['port'] = peer['addr'].partition(':')[2] peer['country'] = info.get('country_name', "") peer['country_code'] = info.get('country_code', "") peer['city'] = info.get('city', None) if info.get('city', None) != None else '' peer['lat'] = info.get('latitude', ""); peer['lon'] = info.get('longitude', ""); peer['subver'] = peer['subver'].replace("/", "") peer['in'] = misc.humanBytes(peer['bytesrecv']) if 'bytesrecv' in peer else 'N/A' peer['out'] = misc.humanBytes(peer['bytessent']) if 'bytessent' in peer else 'N/A' peer['lastsend'] = misc.twitterizeDate(peer['lastsend']) if 'lastsend' in peer else 'N/A' peer['lastrecv'] = misc.twitterizeDate(peer['lastrecv']) if 'lastrecv' in peer else 'N/A' peer['conntime'] = misc.timeSince(peer['conntime']) if 'conntime' in peer else 'N/A' peer['syncnode'] = peer['syncnode'] if 'syncnode' in peer else False currency_codes = {} currency_names = {} currency_symbols = {} for provider_id in connector.config: currency_names[provider_id] = connector.config[provider_id]['name'] currency_symbols[provider_id] = connector.config[provider_id]['symbol'] currency_codes[provider_id] = connector.config[provider_id]['currency'] currency_codes = sorted(currency_codes) page_title = _("Network") context = { 'globals': MainConfig['globals'], 'breadcrumbs': misc.buildBreadcrumbs(current_section, '', currency_names[selected_provider_id]), 'system_errors': connector.errors, 'system_alerts': connector.alerts, 'page_title': page_title, 'page_sections': sections, 'request': request, 'currency_codes': currency_codes, 'currency_names': currency_names, 'currency_symbols': currency_symbols, 'selected_provider_id': selected_provider_id, 'peers': peers, 'notsupported': notsupported } return render(request, 'network/index.html', context)
def get_origin_iata(self): l_avia.debug("------------------- Start get_origin_iata ------------") request = self.request iata = None l_avia.debug(request) if request and settings.GEOIP_PATH: l_avia.debug("GEOIP found") from django.contrib.gis.geoip import GeoIP ip_address = request.META.get('HTTP_X_CLIENT_IP', None) if not ip_address: ip_address = request.META.get('REMOTE_ADDR') g = GeoIP() city_info = g.city(ip_address) or dict() city = city_info.get('city', None) country = city_info.get('country_name', None) l_avia.debug("Tring to find iata with country_en={0}"\ "; city_en={1}; ip_address={2}".format( country, city, ip_address )) iata = AirportIATA.objects.find_iata( country_en=country, city_en=city, ) if iata: l_avia.debug('Origin iata found: {0}'.format(iata)) else: l_avia.debug('Origin iata NOT found... Iata: {0}'.format(iata)) iata = 'MOW' # Moscow l_avia.debug("------------------- End get_origin_iata ------------") return iata
def voter_location_retrieve_from_ip_for_api(ip_address): """ Used by the api :param ip_address: :return: """ g = GeoIP() location = g.city(ip_address) if location is None: # Consider this alternate way of responding to front end: # return HttpResponse('no matching location for IP address {}'.format(ip_address), status=400) response_content = { 'success': True, 'status': 'LOCATION_NOT_FOUND', 'voter_location_found': False, 'voter_location': '', 'ip_address': ip_address, } else: response_content = { 'success': True, 'status': 'LOCATION_FOUND', 'voter_location_found': True, 'voter_location': '{0[city]}, {0[region]} {0[postal_code]}'.format(location), 'ip_address': ip_address, } return HttpResponse(json.dumps(response_content), content_type='application/json')
def gotolink(request,bookmark_id): g = GeoIP() client_ip = request.META['REMOTE_ADDR'] client_geo = g.city(client_ip) client_city = client_geo['city'] + ',' + client_geo['region'] try: b = Bookmark.objects.get(pk=bookmark_id) except Bookmark.DoesNotExist: raise Http404("Weird -- Bookmark does not exist") b.accessCount += 1 b.save() alist = b.accessinfo_set.filter(accessIP__contains=client_ip) if(len(alist)==0): a = b.accessinfo_set.create(accessIP=client_ip,accessCount=1) a.save() elif(len(alist)==1): a = alist[0] a.accessCount += 1 a.save() else: return Http404("Internal accounting error") return HttpResponseRedirect(b.url)
def getRecPlaces(request): #request.session["token-created"]=datetime.datetime.now() if request.session.get('openi-token')==None: return HttpResponseRedirect("/login") # elif OPENiAuthorization().checkIfExpired(request.session.get('token-created')): # return HttpResponseRedirect("/login") lat=50.85 lng= 4.35 g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) #ip='195.177.247.202' #test IP for localhost requests. Remove on deployment city=g.city(ip) #this method puts delay on the request, if not needed should be removed settings={} if request.method == 'POST': settings['educationSettings']=request.POST.get("educationSettings", "") settings['genderSettings']=request.POST.get("genderSettings", "") settings['ageSettings']=request.POST.get("ageSettings", "") settings['interestsSettings']=request.POST.get("interestsSettings", "") settings['daytimeSettings']=request.POST.get("daytimeSettings", "") lat=request.POST.get("latitudeTextbox", "") lng=request.POST.get("longitudeTextbox", "") token=request.POST.get("token", "") userID=request.POST.get("userID", "") #print settings else: token=request.session.get('openi-token') userID=request.session.get('username') if ip and (ip!='127.0.0.1'): lat,lng=g.lat_lon(ip) #print "%s %s" %(lat, lng) timezone=str(tzwhere().tzNameAt(float(lat), float(lng))) utc2 = arrow.utcnow() local = utc2.to(timezone) username=userID # for user in FoursquareKeys.users: # if user['username']==userID: # userID=user['id'] # break if request.method=='POST': if checkIfEnabled(settings['daytimeSettings']): recommender=queryHandlers.RecommenderSECall(token, checkIfEnabled(settings['educationSettings']),checkIfEnabled(settings['genderSettings']), checkIfEnabled(settings['ageSettings']),checkIfEnabled(settings['interestsSettings']),local) else: recommender=queryHandlers.RecommenderSECall(token, checkIfEnabled(settings['educationSettings']),checkIfEnabled(settings['genderSettings']), checkIfEnabled(settings['ageSettings']),checkIfEnabled(settings['interestsSettings']) ) else: recommender=queryHandlers.RecommenderSECall(token, True,True, True,local) #places=[] openiCall=queryHandlers.OpeniCall(token=token) context=openiCall.getContext() context=context["result"][-1]["@data"]["context"] places=recommender.getPlaces(lat,lng) #print places args = {"lat":lat, "long":lng, "city":city, "datetime":local, "places":places, "user":request.user, "settings":settings, "token":token, "context":context, "userID":userID, "username":username} args.update(csrf(request)) return render_to_response('rec-places.html' , args)
def get_global_city_id(request): # if request.COOKIES.get('city'): # city=City.objects.get(city=request.COOKIES.get('city')) # city_id=city.id # print "city_id", city_id # return city_id # else: # return None user_ip = globals.ip # local if user_ip.startswith('127.0.0'): user_ip = '114.69.235.2' g = GeoIP() city=g.city(user_ip)['city'] print "city", city if not city: city = "Pondicherry" if City.objects.filter(city=city).exists(): city = City.objects.get(city=city) city_id=city.id else: country = get_global_country(request) city_model = City() city_model.city = city city_model.country_code = country city_model.country_name = g.country_name(user_ip) city_model.save() city_id = city_model.id print "city_id", city_id return city_id
def index(request): """Docstring.""" print colored("***" * 27, "green") print colored("*** INSIDE `%s`" % inspect.stack()[0][3], "green") g = GeoIP() ip = get_client_ip(request) # ip = "108.162.209.69" country = g.country(ip) city = g.city(ip) print colored("[--- DUMP ---] COUNTRY : %s" % country, "yellow") print colored("[--- DUMP ---] CITY : %s" % city, "yellow") timeline_qs = [] timeline_qs = sorted(chain( Post.objects.all(), Challenge.objects.get_upcoming(), Organization.objects.filter( is_hidden=False, is_deleted=False, )), key=attrgetter("created"))[:10] return render(request, "home/index.html", { "timeline_qs": timeline_qs, })
def get_loc(request): g = GeoIP() city = g.city(get_client_ip(request)) province = None if city: province = city['region'] return province
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country="<foo>") addr = "128.249.1.1" fqdn = "tmc.edu" for query in (fqdn, addr): # Country queries should still work. for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual("US", func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual("United States", func(query)) self.assertEqual({"country_code": "US", "country_name": "United States"}, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual("USA", d["country_code3"]) self.assertEqual("Houston", d["city"]) self.assertEqual("TX", d["region"]) self.assertEqual(713, d["area_code"]) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) lon, lat = (-95.4010, 29.7079) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
def test05_unicode_response(self): "Testing that GeoIP strings are properly encoded, see #16553." g = GeoIP() d = g.city("duesseldorf.de") self.assertEqual('Düsseldorf', d['city']) d = g.country('200.26.205.1') # Some databases have only unaccented countries self.assertIn(d['country_name'], ('Curaçao', 'Curacao'))
def current_location(request): ip = get_real_ip(request) g = GeoIP() if ip is not None: location = g.city(ip) return str(location['city'])+', '+str(location['country_name']) else: return ''
def location(src): g = GeoIP() location = g.city(src) if location is not None: location["charset"] = src return location else: return None
def get_user_location_details(request): g = GeoIP() ip=get_client_ip(request) country = '' city = '' if ip: try: country = g.city(ip)['country_name'] city = g.city(ip)['city'] if not country: country = g.country(ip)['country_name'] except TypeError: pass Result = namedtuple("result", ["city", "country", "ip"]) return Result(city=city, country=country, ip=ip)
def geolocate_user(user_id, ip=None): geo = GeoIP() results = geo.city(ip) User.objects.filter(id=user_id).update( location_country=results.get('country_code'), location_name=results.get('city'), location_latlng=geo.geos(ip))
def export_detail_excel(request): clicks = PromotionsEventClicks.objects.all() g = GeoIP() response = HttpResponse(content_type='application/vnd.ms-excel;charset=utf-8') response['Content-Disposition'] = 'attachment; filename="promotion_tracking.csv"' writer = csv.writer(response) writer.writerow( ['Count', 'Time', 'Title', 'Type', 'id', 'Sub Type', 'Event Location', 'Time', 'IP', 'Host', 'Country', 'Region Shown', 'vid', 'Customer Number', 'Discipline', 'Country']) for click in clicks: if click.ip == 'internal': click.ip = '192.168.1.1' # if not IPAddress(click.ip).is_private(): if not is_local_ip(click.ip): if click.promotion_type == "Event": try: object = SimpleEventPromotion.objects.get(pk=click.promotion_id) promotion_sub_type = object.event_type event_location = map(lambda x: x.region_name, object.regions.all()) except: promotion_sub_type = 'unknown' event_location = 'unknown' else: promotion_sub_type = 'no subtype' event_location = 'web' # If IP is not internal use same logic as plugins to find regions shown ip_country = "unknown" ip_region = "USA" try: host = socket.gethostbyaddr(click.ip)[0] except: host = "unknown" if click.ip != '192.168.1.1': loc = g.city(click.ip) if loc: ip_country = loc['country_code3'] try: ip_region = Web_Region_Country.objects.get(country_UN=ip_country).region except Web_Region_Country.DoesNotExist: ip_region = Web_Region_Country.objects.get(country_UN='USA').region cust_discipline = "unknown" cust_country = "unknown" if click.customer_id: try: cust = Customer.objects.get(pk=click.customer_id) cust_discipline = cust.primary_discipline cust_country = cust.country except: cust_discipline = "unknown" cust_country = "unknown" writer.writerow( [click.pk, click.time, click.promotion_title, click.promotion_type, click.promotion_id, promotion_sub_type, event_location, click.time, click.ip, host, ip_country, ip_region, click.vid, click.customer_id, cust_discipline, cust_country]) return response
def getRecProducts(request): # if not request.user.is_authenticated(): # # Do something for anonymous users. # return HttpResponseRedirect("/login") g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) ip='147.102.1.1' #test IP for localhost requests. Remove on deployment city=g.city(ip) #this method puts delay on the request, if not needed should be removed settings={} if ip and (ip!='127.0.0.1'): lat,lng=g.lat_lon(ip) if request.method == 'POST': settings['educationSettings']=request.POST.get("educationSettings", "") settings['genderSettings']=request.POST.get("genderSettings", "") settings['ageSettings']=request.POST.get("ageSettings", "") settings['interestsSettings']=request.POST.get("interestsSettings", "") settings['daytimeSettings']=request.POST.get("daytimeSettings", "") settings['categorySettings']=request.POST.get("categorySettings", "") settings['methodRecommendation']=request.POST.get("methodRecommendation", "") settings['shopRecommendation']=request.POST.get("shopRecommendation", "") token=request.session.get('openi-token') userID=request.POST.get("userID", "") #print settings else: settings['categorySettings']='all' settings['methodRecommendation']='count' settings['shopRecommendation']='no' token=request.session.get('openi-token') userID=request.session.get('username') timezone=str(tzwhere().tzNameAt(float(lat), float(lng))) utc2 = arrow.utcnow() local = utc2.to(timezone) username=userID #for user in FoursquareKeys.users: # if user['username']==userID: # userID=user['id'] # break openiCall=queryHandlers.OpeniCall(token=token) context=openiCall.getContext() context=context["result"][-1]["@data"]["context"] if request.method=='POST': if checkIfEnabled(settings['daytimeSettings']): recommender=queryHandlers.RecommenderSECall(token, checkIfEnabled(settings['educationSettings']),checkIfEnabled(settings['genderSettings']), checkIfEnabled(settings['ageSettings']),checkIfEnabled(settings['interestsSettings']),local) else: recommender=queryHandlers.RecommenderSECall(token, checkIfEnabled(settings['educationSettings']),checkIfEnabled(settings['genderSettings']), checkIfEnabled(settings['ageSettings']),checkIfEnabled(settings['interestsSettings']) ) else: recommender=queryHandlers.RecommenderSECall(token, True,True, True,local) products=recommender.getProducts(category=settings['categorySettings'], method=settings['methodRecommendation'], shopId=settings['shopRecommendation']) args = { "datetime":local, "products":products, "user":request.user, "settings":settings, "token":token, "productCategories":apiURLs.recommnederProductCategories, "username":username, "context":context} args.update(csrf(request)) return render_to_response("rec-products.html",args)
def get_geoip_coords(request): lat, lng = '', '' geoip = GeoIP() # TODO: Middleware to set REMOTE_ADDR from HTTP_X_FORWARDED_FOR. remote_addr = get_remote_ip(request) geoip_result = geoip.city(remote_addr) if geoip_result: lat = geoip_result.get('latitude', '') lng = geoip_result.get('longitude', '') return lat, lng
def test05_unicode_response(self): "Testing that GeoIP strings are properly encoded, see #16553." g = GeoIP() fqdn = "duesseldorf.de" if self._is_dns_available(fqdn): d = g.city(fqdn) self.assertEqual('Ratingen', d['city']) d = g.country('200.26.205.1') # Some databases have only unaccented countries self.assertIn(d['country_name'], ('Curaçao', 'Curacao'))
def changepass(request): if request.method == "POST": response = verifySignature(request) if response['status'] == "failed": return JsonResponse(response) uid = request.POST.get("uid") passwd = request.POST.get("password") device = [] password = hashlib.sha256(passwd).hexdigest() currentuser = {} try: ipaddress = get_client_ip(request) print ipaddress g = GeoIP() cityinfo = g.city(ipaddress) print cityinfo except Exception as ex: print ex try: appversion = request.META['HTTP_RT_APP_VERSION'] deviceos = request.META['HTTP_RT_DEVICE_OS'] devicetype = request.META['HTTP_RT_DEVICE_TYPE'] ua = request.META['HTTP_USER_AGENT'] deviceid = request.META['HTTP_RT_DEVICE_ID'] devicename = devicetype devicefullname = devicetype + "_" + deviceos + "_" + appversion + "_" + ua except Exception as ex: print ex devicename = "Unknown" devicefullname = "Unknown" + "_" + "Unknown" + "_" + "v0.7.1" + "_" + "mobile" try: # User.objects.filter(Q(username=username) &Q(password=password)) userobject = User.objects.filter(Q(id=uid)).get() if userobject.id == uid: userobject.password = passwd userobject.save() data = {} data['message'] = "sucessfully changed password" data['status'] = "ok" else: data = {} data['message'] = "unable to reset user password" data['status'] = "failed" except Exception as ex: print ex data = {} data['message'] = "unable to reset user password" data['status'] = "failed" return JsonResponse(data) else: data = {} data['message'] = MESSAGE.INVALID_REQUEST_POST data['status'] = "failed" return JsonResponse(data)
def events(request): """Route for the events page - displays the events belonging to the category selected by the user Args: request: request object having get parameters. It has the category ids using which we search for events Returns: Renders a different page which has all the events related to the categories passed """ g = GeoIP() ip_address = request.META.get('HTTP_X_FORWARDED_FOR', '74.125.79.147') geo_location = g.city(ip_address) form = CategoriesForm(request.GET) request_params = { "token": EVENTBRITE_API_KEY, "location.latitude": geo_location['latitude'], "location.longitude": geo_location['longitude'], "location.within": "20mi", "sort_by": "date" } if form.is_valid(): categories_string = ','.join(form.cleaned_data.get('category', [])) request_params = _update_urlencode_request_params( categories_string, 1, request_params) events_list, page_count = _get_events(request_params) previous_events_url, next_events_url = _get_next_previous_event_urls( 1, categories_string, page_count) previous_enabled, next_enabled = _get_previous_next_link_status( page_count, 1) return render_to_response( "EventFinderProject/events.html", { "events_list": events_list, "previous_events_url": previous_events_url, "next_events_url": "?" + next_events_url, "previous": previous_enabled, "next": next_enabled }) else: user_categories = request.GET.get('user_categories', '') page = int(request.GET.get('page', '0')) request_params = _update_urlencode_request_params( user_categories, page, request_params) events_list, page_count = _get_events(request_params) previous_events_url, next_events_url = _get_next_previous_event_urls( page, user_categories, page_count) previous_enabled, next_enabled = _get_previous_next_link_status( page_count, page) return render_to_response( "EventFinderProject/events.html", { "events_list": events_list, "previous_events_url": "?" + previous_events_url, "next_events_url": "?" + next_events_url, "previous": previous_enabled, "next": next_enabled })
def where(request): ip = get_ip(request) geoloc = GeoIP() context = geoloc.city(ip) # geodata = GeoLocator('SxGeoCity.dat', MODE_BATCH | MODE_MEMORY) # location = geodata.get_location(ip, detailed=True) return render( request, 'eshop/where.html', {'context': context, 'myip': ip} )
def update_geo_info_task(ip_address, profile_id): try: ip = '188.141.70.110' if ip_address == '127.0.0.1' else ip_address if ip: g = GeoIP() city = g.city(ip) country = g.country(ip) print("Updated user location") except Exception as e: logger.exception(e) pass
def test_loc(request): ip = get_real_ip(request) if ip is not None: g = GeoIP() render_var = g.city(ip)['city'] else: # we don't have a real, public ip address for user render_var = 'Not real' return render(request, 'test_loc.html', {'render_var': render_var})
def detect_geo(self): if self.ip and self.counter == 0: from django.contrib.gis.geoip import GeoIP, GeoIPException try: g = GeoIP() info = g.city(self.ip) or dict() for (k, v) in info.items(): setattr(self, 'ip_%s' % k, v) except GeoIPException: pass
def get_geo_ip_data(ip_address): if not HAS_GEOIP or not TRACK_USING_GEOIP: return geoip_data = None try: gip = GeoIP(cache=GEOIP_CACHE_TYPE) geoip_data = gip.city(ip_address) except GeoIPException as e: msg = 'Error getting GeoIP data for IP "{0}"'.format(ip_address) log.exception(msg) return geoip_data
def geoip_data(self): "Attempts to retrieve MaxMind GeoIP data based upon the visitor's IP" if not HAS_GEOIP or not TRACK_USING_GEOIP: return if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=GEOIP_CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: log.error('Error getting GeoIP data for IP "%s": %s' % (self.ip_address, traceback.format_exc())) return self._geoip_data
def return_city_country(ip, current_user): g = GeoIP() location=g.city(ip) try: current_user.city=location['city'] current_user.country=location['country_code'] current_user.latitude=location['latitude'] current_user.longitude=location['longitude'] current_user.save() except TypeError: city='local machine' country='local' #def find_tutor(query):
def is_local(request): g = GeoIP() try: addr = request.META['REMOTE_ADDR'] addr = '65.112.8.3' loc = g.city(addr) city, state, country = loc['city'], loc['region'], loc['country_code'] ans = ((city == 'Cambridge' or city == 'Boston') and country == 'US' and state == 'MA') if ans: return HttpResponse('True') else: return HttpResponse('False') except (KeyError, TypeError): return HttpResponse('Unknown')
def handle(self, *args, **options): cur = connection.cursor() g = GeoIP() cur.execute( "SELECT id, release_id, created, ip4addr FROM apps_download") for id, release_id, created, ip4addr in cur.fetchall(): release = Release.objects.get(id=release_id) app = release.app when = created.date() a_str = '{0:5} {1:30} {2:15} {3:10} {4:15}'.format( id, app.fullname, release.version, str(when), ipaddr_long_to_str(ip4addr)) sys.stdout.write(a_str + '\n') sys.stdout.flush() dl = Download.objects.create(release=release, when=when, ip4addr=ip4addr) dl.save() increment_count(ReleaseDownloadsByDate, release=release, when=when) increment_count(ReleaseDownloadsByDate, release=None, when=when) geoinfo = g.city(ipaddr_long_to_str(ip4addr)) if geoinfo: country_geoloc, _ = GeoLoc.objects.get_or_create( country=geoinfo['country_code'], region='', city='') increment_count(AppDownloadsByGeoLoc, app=app, geoloc=country_geoloc) increment_count(AppDownloadsByGeoLoc, app=None, geoloc=country_geoloc) if geoinfo.get('city'): city_geoloc, _ = GeoLoc.objects.get_or_create( country=geoinfo['country_code'], region=geoinfo['region'], city=geoinfo['city']) increment_count(AppDownloadsByGeoLoc, app=app, geoloc=city_geoloc) increment_count(AppDownloadsByGeoLoc, app=None, geoloc=city_geoloc) sys.stdout.write('\n')
def geoip_data(self): """Attempt to retrieve MaxMind GeoIP data based on visitor's IP.""" if not HAS_GEOIP or not TRACK_USING_GEOIP: return if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=GEOIP_CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: msg = 'Error getting GeoIP data for IP "{0}"'.format( self.ip_address) log.exception(msg) return self._geoip_data