def test04_city(self, gethostbyname): "GeoIP city querying methods." gethostbyname.return_value = '128.249.1.1' g = GeoIP2(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query) self.assertEqual( { 'country_code': 'US', 'country_name': 'United States' }, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('US', d['country_code']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) for e1, e2 in (geom.tuple, g.coords(query), g.lon_lat(query), g.lat_lon(query)): self.assertIsInstance(e1, float) self.assertIsInstance(e2, float)
def get_user_location(ip): try: g = GeoIP2() location = g.city(ip) return location, None except Exception as e: return None, str(e)
def test04_city(self, gethostbyname): "GeoIP city querying methods." gethostbyname.return_value = '75.41.39.1' g = GeoIP2(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query) self.assertEqual( { 'country_code': 'US', 'country_name': 'United States' }, g.country(query)) # City information dictionary. d = g.city(query) self.assertEqual('NA', d['continent_code']) self.assertEqual('North America', d['continent_name']) self.assertEqual('US', d['country_code']) self.assertEqual('Dallas', d['city']) self.assertEqual('TX', d['region']) self.assertEqual('America/Chicago', d['time_zone']) self.assertFalse(d['is_in_european_union']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) for e1, e2 in (geom.tuple, g.coords(query), g.lon_lat(query), g.lat_lon(query)): self.assertIsInstance(e1, float) self.assertIsInstance(e2, float)
def get_weather(self, request): city_name = self.name if city_name is None: forwarded = request.META.get('HTTP_X_FORWARDED_FOR') if forwarded: user_ip = forwarded.split(',')[0] else: user_ip = request.META.get('REMOTE_ADDR') geo = GeoIP2() try: city = geo.city(user_ip) city_name = ','.join([city.get('city'), city.get('country_code')]) except AddressNotFoundError: city_name = self.DEFAULT_CITY units = request.GET.get('units', self.OWM_DEFAULT_UNITS) url = f'{self.BASE_URL}weather?q={city_name}&units={units}&lang=ru&appid={OWM_API_KEY}' response = requests.get(url).json() if response['cod'] == 200: if units == 'metric': response['wind']['speed'] = f"{response['wind']['speed']} {self.UNITS['metric']['wind_speed']}" response['main']['pressure'] = f"{round(response['main']['pressure'] * 0.750062)} {self.UNITS['metric']['pressure']}" else: response['wind']['speed'] = f"{response['wind']['speed']} {self.UNITS['imperial']['wind_speed']}" response['main']['pressure'] = f"{round(response['main']['pressure'])} {self.UNITS['imperial']['pressure']}" response['visibility'] = round(response['visibility'] / 1000, 1) return response
def ip_to_location_info(ip): """ Get a dictionary of location info for a given IP address. The format of the dictionary is the same provided by the functions in django.contrib.gis.geoip2.base.GeoIP2. """ if not HAS_GEOIP2: return None from django.contrib.gis.geoip2 import GeoIP2 try: g = GeoIP2() except Exception as e: warnings.warn(str(e)) return None try: return g.city(ip) except Exception: try: return g.country(ip) except Exception as e: warnings.warn(str(e))
def reg_basic(request): autoLogout(request) username = request.POST["username"] password = request.POST["password"] email = request.POST["email"] nric = request.POST["nric"] phone_number = request.POST["phone_number"] if request.session.get("status") != None: return HttpResponse(appres_fatal_error) if checkAndDel(username): return HttpResponse("USERNAME EXISTS") #else ip = get_client_ip(request) g = GeoIP2() info = g.city(ip) geolocation = str(info.get("city")) + ", " + str(info.get("country_name")) newUser = MyUser(username=username, password=password, email=email, nric=nric, phone_number=phone_number, geolocation=geolocation) newUser.save() request.session['status'] = SESSIONSTATUS['REG_BASICINFO'] request.session['username'] = username request.session['last_sent'] = int(timezone.now().timestamp()) request.session['time'] = int(timezone.now().timestamp()) #SEND EMAIL sendEmailSaveCode(username) return HttpResponse(appres_success)
def get(self, request): from django.contrib.gis.geoip2 import GeoIP2 ip = get_client_ip(request) if ip == '127.0.0.1': ip = '200.35.194.69' g = GeoIP2() country = g.country(ip) pais = Country.objects.get(country=country['country_name']) data_onix = PriceOnix.objects.filter(country=pais)[:1] data_onix = data_onix[0] return Response({ 'btc_onx_buy': '{:f}'.format(data_onix.btc_onx_buy), 'onx_local_buy': data_onix.onx_bs_buy, 'usd_onx_buy': data_onix.usd_onx_buy, 'btc_onx_sell': '{:f}'.format(data_onix.btc_onx_sell), 'onx_local_sell': data_onix.onx_bs_sell, 'usd_onx_sell': data_onix.usd_onx_sell, 'country': pais.country, 'code_currency': pais.code_currency })
def redirector(request): offer_id = request.GET.get('offer_id', '') wm_id = request.GET.get('wmid', '') try: offer = Offer.objects.get(id=int(offer_id)) wm = Webmaster.objects.get(id=int(wm_id)) except: referer_url = request.META.get('HTTP_REFERER') if referer_url: return redirect(referer_url) else: return HttpResponseNotFound() click = Click.objects.create(offer=offer, webmaster=wm) click.client_user_agent = request.META['HTTP_USER_AGENT'] client_ip = get_client_ip(request) click.client_ip = client_ip try: g = GeoIP2().city(client_ip) click.client_country = g['country_name'] click.client_timezone = g['time_zone'] click.client_city = g['city'] except: pass click.save() return redirect(offer.url)
def login_basic(request): autoLogout(request) username = request.POST["username"] password = request.POST["password"] if request.session.get('status') != None: return HttpResponse(appres_fatal_error) if checkAndDel(username) == False: return HttpResponse("NO SUCH USER") user = MyUser.objects.get(username=username) ip = get_client_ip(request) g = GeoIP2() info = g.city(ip) geolocation = str(info.get("city")) + ", " + str(info.get("country_name")) if (geolocation != user.geolocation): sendEmailLocation(username=username) user.tried += 1 user.save() if (user.tried >= 3): sendEmailLocation(username=username) if (user.password == password): user.tried = 0 user.save() request.session["status"] = SESSIONSTATUS["LOGIN_BASICINFO"] request.session["username"] = request.POST["username"] request.session["last_sent"] = int(timezone.now().timestamp()) request.session["time"] = int(timezone.now().timestamp()) #auto send email sendEmailSaveCode(username) return HttpResponse(appres_success) else: return HttpResponse("WRONG PASSWORD")
def heatmaplocations(request): geoip2 = GeoIP2() data = {} latitude = [] longitude = [] result_dict = [] data = LogsHolder.objects.all().values("remoteAddr") for datum in data: lat, lng = geoip2.lat_lon(datum['remoteAddr']) latitude.append(lat) longitude.append(lng) df = pd.DataFrame({'latitude': latitude, 'longitude': longitude}) result = df.groupby(['latitude', 'longitude']).size().reset_index() for index, row in result.iterrows(): content = { 'latitude': row['latitude'], 'longitude': row['longitude'], 'count': row[0] } result_dict.append(content) data = { "heatmaplocations": result_dict, } return JsonResponse(data)
def get_client_data(): g = GeoIP2() ip = get_random_ip() try: return g.city(ip) except geoip2.errors.AddressNotFoundError: return None
def test_check_query(self, gethostbyname): g = GeoIP2() self.assertEqual(g._check_query("127.0.0.1"), "127.0.0.1") self.assertEqual( g._check_query("2002:81ed:c9a5::81ed:c9a5"), "2002:81ed:c9a5::81ed:c9a5" ) self.assertEqual(g._check_query("invalid-ip-address"), "expected")
def test06_ipv6_query(self): "GeoIP can lookup IPv6 addresses." g = GeoIP2() d = g.city("2002:81ed:c9a5::81ed:c9a5") # IPv6 address for www.nhm.ku.edu self.assertEqual("US", d["country_code"]) self.assertEqual("Lawrence", d["city"]) self.assertEqual("KS", d["region"])
def get_client_city_data(ip_address): g = GeoIP2() try: return g.city(ip_address) except: return None
def get_client_details(request) -> dict: ''' Given valid request returns user's ip, location and user-agent. ''' if not request: return dict() client_ip, is_routable = get_client_ip(request) client_ip = client_ip if client_ip and is_routable else None location = '' if client_ip: result = GeoIP2().city(client_ip) location = '{city}, {country}'.format( country=result.get('country_name', ''), city=result.get('city', ''), ) user_agent = request.META.get('HTTP_USER_AGENT', '') if user_agent: user_agent = str(parse_ua(user_agent)) return { 'ip': client_ip, 'location': location, 'user_agent': user_agent, }
def pixel_gif(request): PIXEL_GIF_DATA = base64.b64decode("") info = request.GET # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') # # if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') if (ip == '127.0.0.1'): ip = '118.69.213.98' g = GeoIP2('geoip2_db') logger.warn( "pixel_gif!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") logger.warn("url" + info['url']) logger.warn("title" + info['t']) logger.warn("!!!!!!!!!!!IP!!!!!!!!:" + ip) logger.warn("!!!!!!!!!!!!!!!!!!country" + json.dumps(g.country(ip))) logger.warn("!!!!!!!!!!!!!!!!!!city:" + json.dumps(g.city(ip))) logger.warn( "pixel_gif!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") return HttpResponse(PIXEL_GIF_DATA, content_type='image/gif')
def get(self, request): loc = serialize('geojson', Rides.objects.all()) dec_loc = json.loads(loc) obj = Rides.objects.all() paginator = Paginator(obj, 12) query = request.GET.get('q', None) if query is not None: rides = obj.filter(Q(location_name__icontains=query)) paginator = Paginator(rides, 12) page = request.GET.get('page') rides = paginator.get_page(page) g = GeoIP2() ip = "185.86.151.11" # self.get_client_ip(request) user_loc_lat = g.lat_lon(ip)[0] user_loc_lon = g.lat_lon(ip)[1] context = { 'dec_loc': loc, 'rides': rides, 'user_loc_lat': user_loc_lat, 'user_loc_lon': user_loc_lon, 'obj': obj } return render(request, 'Home.html', context)
def get_location_from_ip(ip_address): """Get the location associated with the provided IP address. Args: ip_address (str): The IP address to lookup. Returns: dict: The GeoIP location data dictionary. """ city = {} if not ip_address: return city try: geo = GeoIP2() try: city = geo.city(ip_address) except AddressNotFoundError: pass except Exception as e: logger.warning( f'Encountered ({e}) while attempting to retrieve a user\'s geolocation' ) return city
def paygol_ok(request): ip = get_ip(request) g = GeoIP2() try: country = g.country(ip) if country["country_name"] == "Georgia": user_language = 'ka_GE' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) elif country["country_name"] == "Russia" or country[ "country_name"] == "Ukraine" or country[ "country_name"] == "Belarus" or country[ "country_name"] == "Latvia" or country[ "country_name"] == "Lithuania" or country[ "country_name"] == "Moldova" or country[ "country_name"] == "Estonia": user_language = 'ru' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) except: pass messages.info(request, 'Your Payment was SUCCESSFUL!') return HttpResponseRedirect("/cabinet")
def test06_ipv6_query(self): "GeoIP can lookup IPv6 addresses." g = GeoIP2() d = g.city('2002:81ed:c9a5::81ed:c9a5') # IPv6 address for www.nhm.ku.edu self.assertEqual('US', d['country_code']) self.assertEqual('Lawrence', d['city']) self.assertEqual('KS', d['region'])
def payment_index(request): ip = get_ip(request) g = GeoIP2() try: country = g.country(ip) if country["country_name"] == "Georgia": user_language = 'ka_GE' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) elif country["country_name"] == "Russia" or country[ "country_name"] == "Ukraine" or country[ "country_name"] == "Belarus" or country[ "country_name"] == "Latvia" or country[ "country_name"] == "Lithuania" or country[ "country_name"] == "Moldova" or country[ "country_name"] == "Estonia": user_language = 'ru' translation.activate(user_language) response = HttpResponse() response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language) except: pass user = request.user if request.user.is_authenticated: widget = Widget( user.id, # id of the end-user who's making the payment 'p4_1', # widget code, e.g. p1; can be picked inside of your merchant account [], # array of products - leave blank for Virtual Currency API {'email': '*****@*****.**'} # additional parameters ) return HttpResponseRedirect(widget.get_url()) else: return HttpResponseRedirect("/")
def dashboard(request): page_view = {} visitor_view = {} country_name = {} count_users = {} geolocation = {} g = GeoIP2() pageviews = Pageview.objects.distinct() visitors = Visitor.objects.distinct() for page in pageviews: pages = pageviews.filter(url=page.url) try: page_view[page.url] += pages.count() except KeyError as e: page_view.update({page.url: pages.count()}) for visitor in visitors: try: visitor_view[(visitor.start_time).strftime("%Y-%m-%d")] += [ visitor.session_key ] country_name[g.city(visitor.ip_address)['country_name']] += [ g.city(visitor.ip_address)['country_name'] ] count_users[visitor.user] += [visitor.user] geolocation[g.city(visitor.ip_address)['country_name']] += [ g.city(visitor.ip_address)['country_name'], g.city(visitor.ip_address)['latitude'], g.city(visitor.ip_address)['longitude'] ] except (KeyError, AddressNotFoundError) as e: try: visitor_view.update({ (visitor.start_time).strftime("%Y-%m-%d"): [visitor.session_key] }) country_name.update({ g.city(visitor.ip_address)['country_name']: [g.city(visitor.ip_address)['country_name']] }) geolocation.update({ g.city(visitor.ip_address)['country_name']: [ g.city(visitor.ip_address)['country_name'], g.city(visitor.ip_address)['latitude'], g.city(visitor.ip_address)['longitude'] ] }) count_users.update({visitor.user: [visitor.user]}) except (KeyError, AddressNotFoundError) as e: pass return render( request, 'wagalytics/dashboard.html', { 'pageview': page_view, 'visitor': visitor_view, 'count_pageview': pageviews.count(), 'count_visitor': visitors.count(), 'country_name': country_name, 'count_users': count_users, 'geolocation': geolocation, })
def test04_city(self): "GeoIP city querying methods." g = GeoIP2(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) ) # City information dictionary. d = g.city(query) self.assertEqual('US', d['country_code']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) 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 index(request): # Converts user's ip to lat lon geoDir = (os.path.join( os.path.dirname(__file__), 'GEOIP_PATH/GeoLite2-City_20190305/GeoLite2-City.mmdb')) g = GeoIP2(geoDir) ip = request.META.get('REMOTE_ADDR', None) # starting location loc = '' if ip == '127.0.0.1': # Default is UCR loc = [33.9737, -117.3281] else: loc = g.lat_lon(ip) # displays map m = folium.Map(location=loc, zoom_start=5) # Tweets #tweets = [[33.9550573,-117.38889023, 'Alpha'], [34.05139929,-117.19333151, 'Beta'], [33.88303718,-117.20156382, 'Gamma'], [34.03881436,-117.31486311,'Delta']] #tweets = {'1': [33.9550573,-117.38889023], '2': [34.05139929,-117.19333151], '3': [33.88303718,-117.20156382], '4': [34.03881436,-117.31486311]} #tweets = {[33.9550573,-117.38889023]: '1', [34.05139929,-117.19333151]: '2', [33.88303718,-117.20156382]: '3', [34.03881436,-117.31486311]: '4'} tweetLoc = (os.path.join(os.path.dirname(__file__), 'tweets/t_tweets.json')) tweetJson = tweetIndex.readFile(tweetLoc) tweets = tweetIndex.collect_tweet_texts(tweetJson) tweet_data = tweets[0] tweet_json = tweets[1] tweetIndex.updateJson(tweet_json) tweetIndex.indexTweets(tweet_json) #tweetGeo = folium.GeoJson(tweets).add_to(m) """for tweet in tweets: folium.Marker( location=[tweet[0],tweet[1]], popup=tweet[2] ).add_to(m)""" # Searchbar """tweetSearch = Search( layer=tweetGeo, geom_type='Point', placeholder="Search Tweets", #search_label='popup' ).add_to(m)""" # puts map to html tweetIndexFileLoc = (os.path.join(os.path.dirname(__file__), 'templates/foliumMap.html')) m.save(tweetIndexFileLoc) tweetIndexFile = open(tweetIndexFileLoc) return render(request, 'index.html')
def index(request, city=None, gender=None): """ Index view: - get IP address of user - get city by IP address - send request to weather API - process possible errors - form the path to recommended outfit - render the index view with weather and clothes data """ # Get city of user unless it is submitted if city == None: # Get IP address from the request ip = addon.get_client_ip(request) # If using local IP address set default city to Moscow if ip == '127.0.0.1': city = "Moscow" else: # Get city from IP address g = GeoIP2() city = g.city(ip)['city'] # Send request to the Weather API try: url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=8b382ef4df4488ef794338a7819f3c9d' r = requests.get(url.format(city)).json() # Parse the weather to dictionary city_weather = { 'flag': True, 'city': city, 'temperature': int(r["main"]["temp"]), 'main': r["weather"][0]["main"], 'description': r["weather"][0]["description"], 'icon': r["weather"][0]["icon"], } # Form the path to the recommended outfit cloth_pic = addon.form_cloth_pic_path(gender, city_weather) except: # Fill in the void dictionary city_weather = { 'flag': False, 'city': "Incorrect city!", 'temperature': None, 'main': None, 'description': None, 'icon': None, } #Form void paths cloth_pic = "None" # Form injection dictionary for clothes clothes_dict = {'gender': gender, 'cloth_pic': cloth_pic} # Form context for insertion to the template context = {'city_weather' : city_weather, 'clothes':clothes_dict} # Render the index view return render(request, 'weather_n_clothes/index.html', context)
def geoip(): global _geoip if _geoip is None: try: _geoip = GeoIP2() except Exception as e: warnings.warn(str(e)) return _geoip
def create_word_timestamp(self, request): g = GeoIP2() try: requested_location = g.country_name(request.META['REMOTE_ADDR']) except: requested_location = "Unknown" WordTimeStamp.objects.create(word=self.get_object(), location=requested_location).save()
def test05_unicode_response(self): "GeoIP strings should be properly encoded (#16553)." g = GeoIP2() d = g.city("nigde.edu.tr") self.assertEqual('Niğde', d['city']) d = g.country('200.26.205.1') # Some databases have only unaccented countries self.assertIn(d['country_name'], ('Curaçao', 'Curacao'))
def get_client_data(): # g = GeoIP2() # Através desse objetos encontraremos valores ip = get_random_ip() # Variável recebendo a funçao que cria ips dinamicamente try: # Tenta return g.city(ip) # Recebemos um ip e tentamos retornar a cidade desse ip except geoip2.errors.AddressNotFoundError: # Caso nao encontremos a cidade fornecida através do ip retornamos o # erro: AddressNotFoundError e None return None
def get_geoip_country(self, request): try: GeoIP2 = get_geoip_module() if GeoIP2 is None: return False return GeoIP2().country_code(get_client_ip(request)).lower() except: return False