def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("profile_edit_location_done")) else: form = LocationForm(instance=profile) template = "member/profile/location.html" data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, 'geoip': geoip } return render_to_response(template, data, context_instance=RequestContext(request))
def cidade_index(request, cidade_slug): cidade = Cidade.objects.get(slug=cidade_slug) cidades_disponiveis = Cidade.objects.all() ofertas = Oferta.objects.filter(ativo=True) destaque = Oferta.objects.filter(cidade=cidade, destaque=True, ativo=True) #geoprocessamento ip_address = request.META.get('REMOTE_ADDR') g = GeoIP() #local_full_cliente = g.city(ip_address) local_full_cliente = g.city('201.22.164.216') cidade_cliente = local_full_cliente.get('city') print(cidade_cliente) if ofertas: try: oferta_estreia = ofertas.filter(estreando=True)[0] except IndexError: oferta_estreia = ofertas[0] outras_ofertas = ofertas.exclude(pk=oferta_estreia.pk) else: oferta_estreia = None outras_ofertas = [] return render_to_response( 'index.html', locals(), context_instance=RequestContext(request), )
def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get("ip") == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() request.user.message_set.create(message=_("Your profile information has been updated successfully.")) signal_responses = signals.post_signal.send(sender=location, request=request, form=form) last_reponse = signals.last_response(signal_responses) if last_reponse: return last_response else: form = LocationForm(instance=profile) template = "userprofile/profile/location.html" data = {"section": "location", "GOOGLE_MAPS_API_KEY": GOOGLE_MAPS_API_KEY, "form": form, "geoip": geoip} signals.context_signal.send(sender=location, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request))
def test01_init(self): "Testing GeoIP initialization." g1 = GeoIP() # Everything inferred from GeoIP path path = settings.GEOIP_PATH g2 = GeoIP(path, 0) # Passing in data path explicitly. g3 = GeoIP.open(path, 0) # MaxMind Python API syntax. for g in (g1, g2, g3): self.assertEqual(True, bool(g._country)) self.assertEqual(True, bool(g._city)) # Only passing in the location of one database. city = os.path.join(path, 'GeoLiteCity.dat') cntry = os.path.join(path, 'GeoIP.dat') g4 = GeoIP(city, country='') self.assertEqual(None, g4._country) g5 = GeoIP(cntry, city='') self.assertEqual(None, g5._city) # Improper parameters. bad_params = (23, 'foo', 15.23) for bad in bad_params: self.assertRaises(GeoIPException, GeoIP, cache=bad) if isinstance(bad, basestring): e = GeoIPException else: e = TypeError self.assertRaises(e, GeoIP, bad, 0)
def neighborhood_monitoring(request, template="geotagging/view_neighborhood_monitoring.html", content_type_name=None, distance_lt_km=None): """ Direct the user to a template that is able to render the `kml_neighborhood_feed` on a google map. This feed can be restricted based on the content type of the element you want to get. """ if distance_lt_km == None: distance_lt_km = 10 gip=GeoIP() if request.META["REMOTE_ADDR"] != "127.0.0.1": user_ip = request.META["REMOTE_ADDR"] else: user_ip = "populous.com" user_location_pnt = gip.geos(user_ip) kml_feed = reverse("geotagging-kml_neighborhood_feed", kwargs={"distance_lt_km":distance_lt_km}) criteria_pnt = { "point__distance_lt" : (user_location_pnt, D(km=float(distance_lt_km)) ) } geotag_points = Point.objects.filter(**criteria_pnt).distance(user_location_pnt).order_by("-distance") context = RequestContext(request, { "user_ip" : user_ip, "user_location_pnt" : user_location_pnt, "geotag_points" : geotag_points, "user_city" : gip.city(user_ip), "kml_feed" : kml_feed, }) return render_to_response(template,context_instance=context)
def save(self,ip_address, *args, **kwargs): g = GeoIP() lat, lon = g.lat_lon(ip_address) user_location = super(registerForm, self).save(commit=False) user_location.latitude = lat user_location.longitude = lon user_location.save(*args, **kwargs)
def neighborhood_monitoring(request, template="geotags/view_neighborhood_monitoring.html", content_type_name=None, distance_lt_km=None): """ Direct the user to a template that is able to render the `kml_neighborhood_feed` on a google map. This feed can be restricted based on the content type of the element you want to get. """ if distance_lt_km == None: distance_lt_km = 10 gip=GeoIP() if request.META["REMOTE_ADDR"] != "127.0.0.1": user_ip = request.META["REMOTE_ADDR"] else: user_ip = "populous.com" user_location_pnt = gip.geos(user_ip) kml_feed = reverse("geotags-kml_neighborhood_feed", kwargs={"distance_lt_km":distance_lt_km}) criteria_pnt = { "point__distance_lt" : (user_location_pnt, D(km=float(distance_lt_km)) ) } geotag_points = Point.objects.filter(**criteria_pnt).distance(user_location_pnt).order_by("-distance") context = RequestContext(request, { "user_ip" : user_ip, "user_location_pnt" : user_location_pnt, "geotag_points" : geotag_points, "google_key" : settings.GOOGLE_MAPS_API_KEY, "user_city" : gip.city(user_ip), "kml_feed" : kml_feed, }) return render_to_response(template,context_instance=context)
def location(request): """ Location selection of the user profile """ profile = request.user.get_profile() geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = UserLocationForm(request.POST, instance=profile) if form.is_valid(): form.save() messages.success(request, _("Your profile information has been updated successfully."), fail_silently=True) #signal_responses = signals.post_signal.send(sender=location, request=request, form=form) #last_response = signals.last_response(signal_responses) #if last_response: # return last_response else: form = UserLocationForm(instance=profile) #signals.context_signal.send(sender=location, request=request, context=data) return render_to_response("map/location_form_update.html", \ { 'GOOGLE_MAPS_API_KEY': settings.MAP_GOOGLE_MAPS_API_KEY, \ 'form': form, 'geoip': geoip }, context_instance=RequestContext(request))
def process_request(self, request): from django.conf import settings from meegloo.international.models import Country try: from django.contrib.gis.utils import GeoIP except ImportError: request.country = Country.objects.get( pk = getattr(settings, 'COUNTRY_ID') ) return g = GeoIP() ip = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_IP', request.META.get('REMOTE_ADDR')) ) if ip != '127.0.0.1': d = g.country(ip) code = d['country_code'] request.country = Country.objects.get(code = code) else: pk = getattr(settings, 'COUNTRY_ID') request.country = Country.objects.get(pk = pk)
def kml_neighborhood_feed(request, template="geotags/geotags.kml", distance_lt_km=None ,content_type_name=None, object_id=None): """ Return a KML feed of all the geotags in a around the user. This view takes an argument called `distance_lt_km` which is the radius of the permeter your are searching in. This feed can be restricted based on the content type of the element you want to get. """ gip=GeoIP() if request.META["REMOTE_ADDR"] != "127.0.0.1": user_ip = request.META["REMOTE_ADDR"] else: user_ip = "populous.com" user_location_pnt = gip.geos(user_ip) criteria_pnt = { "point__distance_lt" : (user_location_pnt, D(km=float(distance_lt_km)) ) } if content_type_name: criteria_pnt["content_type__name"]==content_type_name geotags = Point.objects.filter(**criteria_pnt) context = RequestContext(request, { 'places' : geotags.kml(), }) return render_to_kml(template,context_instance=context)
def location(request): """ Location selection of the user profile """ profile, created = Profile.objects.get_or_create(user=request.user) geoip = hasattr(settings, "GEOIP_PATH") if geoip and request.method == "GET" and request.GET.get('ip') == "1": from django.contrib.gis.utils import GeoIP g = GeoIP() c = g.city(request.META.get("REMOTE_ADDR")) if c and c.get("latitude") and c.get("longitude"): profile.latitude = "%.6f" % c.get("latitude") profile.longitude = "%.6f" % c.get("longitude") profile.country = c.get("country_code") profile.location = unicode(c.get("city"), "latin1") if request.method == "POST": form = LocationForm(request.POST, instance=profile) if form.is_valid(): form.save() request.user.message_set.create(message=_("Your profile information has been updated successfully.")) signal_responses = signals.post_signal.send(sender=location, request=request, form=form) last_reponse = signals.last_response(signal_responses) if last_reponse: return last_response else: form = LocationForm(instance=profile) template = "userprofile/profile/location.html" data = { 'section': 'location', 'GOOGLE_MAPS_API_KEY': GOOGLE_MAPS_API_KEY, 'form': form, 'geoip': geoip } signals.context_signal.send(sender=location, request=request, context=data) return render_to_response(template, data, context_instance=RequestContext(request))
def kml_neighborhood_feed(request, template="geotagging/geotagging.kml", distance_lt_km=None ,content_type_name=None, object_id=None): """ Return a KML feed of all the geotagging in a around the user. This view takes an argument called `distance_lt_km` which is the radius of the permeter your are searching in. This feed can be restricted based on the content type of the element you want to get. """ from django.contrib.gis.utils import GeoIP gip=GeoIP() if request.META["REMOTE_ADDR"] != "127.0.0.1": user_ip = request.META["REMOTE_ADDR"] else: user_ip = "populous.com" user_location_pnt = gip.geos(user_ip) criteria_pnt = { "point__distance_lt" : (user_location_pnt, D(km=float(distance_lt_km)) ) } if content_type_name: criteria_pnt["content_type__name"]==content_type_name geotagging = Point.objects.filter(**criteria_pnt) context = RequestContext(request, { 'places' : geotagging.kml(), }) return render_to_kml(template,context_instance=context)
def create_gateway(sender, instance=None, created=False, **kwargs): """ create root domain of user """ if created: geo = GeoIP() data = geo.city(instance.ip) instance.city = data['city'] instance.country = data['country_name'] instance.save()
def get_local(ip): from django.contrib.gis.utils import GeoIP g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip)['city'] else: city = 'Sao Paulo' # default city return city
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 getLocation(self): g = GeoIP() ip = request.META.get("REMOTE_ADDR", None) if ip: city = g.city(ip)["city"] return city else: print "nothing"
def _cidade_cliente(request): #geo ip_address=request.META.get('REMOTE_ADDR') g = GeoIP() #local_full_cliente = g.city(ip_address) local_full_cliente = g.city('201.22.164.216') cidade_cliente = local_full_cliente.get('city') uni = cidade_cliente.decode('cp1252') cidade_cliente = uni.encode('utf8') return cidade_cliente
def getLocation(self): g = GeoIP() ip = request.META.get('REMOTE_ADDR',None) if ip: city = g.city(ip)['city'] return city else : print "nothing"
def _cidade_cliente(request): #geo ip_address = request.META.get('REMOTE_ADDR') g = GeoIP() #local_full_cliente = g.city(ip_address) local_full_cliente = g.city('201.22.164.216') cidade_cliente = local_full_cliente.get('city') uni = cidade_cliente.decode('cp1252') cidade_cliente = uni.encode('utf8') return cidade_cliente
def whereami(request): g = GeoIP() remote_ip = request.META['REMOTE_ADDR'] if remote_ip == '127.0.0.1': remote_ip = get_my_ip() remote_location = g.city(remote_ip) if remote_location: return render_to_response('gmaps.html', {'remote_location': remote_location, 'GOOGLE_MAPS_API_KEY':settings.GOOGLE_MAPS_API_KEY}) else: # localhost ip cannot be found return render_to_response('not_found.html')
def get_geoIP(request): # marseille = Point(5.3697800, 43.2964820) clermont = Point(3.0870250, 45.7772220) ip = request.META.get('REMOTE_ADDR', None) g = GeoIP(path=settings.PROJECT_PATH + '/config/GEO/') if ip and g.city(ip): return (Point(g.city(ip)['longitude'], g.city(ip)['latitude']), g.city(ip)['city']) else: return getattr(settings, 'DEFAULT_MAIN_CITY', (clermont, u'Clermont-Fd')) # default city
def process_request(self, request): request.LOCATION_DATA = False ip = request.META.get('HTTP_X_FORWARDED_FOR', '')\ or request.META.get('HTTP_X_REAL_IP', '')\ or request.META.get('REMOTE_ADDR', '') if ip: g = GeoIP() if settings.DEBUG: ip = '178.92.248.224' request.LOCATION_DATA = g.city(ip)
def get_geo(video): latitude = 0.0 longitude = 0.0 g = GeoIP() if settings.GEOIP_PATH: try: data = g.city(video.job_set.all()[0].ip) if data: latitude = float(data['latitude']) longitude = float(data['longitude']) except StandardError, e: LOGGER.debug(str(e))
def whereis(request, ip): g = GeoIP() ip_match = re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b') try: remote_ip = ip_match.findall(ip)[0] except: remote_ip = '' remote_location = g.city(remote_ip) if remote_location: return render_to_response('gmaps.html', {'remote_location': remote_location, 'GOOGLE_MAPS_API_KEY':settings.GOOGLE_MAPS_API_KEY}) else: # localhost ip cannot be found return render_to_response('not_found.html')
def get_geoip_position(request): """Returns the user's position as a (lat, lng) tuple based on his IP.""" result = (None, None) g = GeoIP() ip = (request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')) result = g.lon_lat(ip) if result is None: ip = settings.SERVER_IP result = g.lon_lat(ip) if result is None: return None return (result[1], result[0])
def get_country_code(request): 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 not ip: return '' g = GeoIP() return g.country(ip)['country_code'] or ''
def browse_offers(request): """ """ if request.user.is_authenticated(): userprofile = request.user.get_profile() else: userprofile = None if request.method == 'POST' or request.GET.get('page'): if request.is_ajax(): return list_offers(request) offers, form = get_offers(request.REQUEST, {'asking_userprofile':userprofile}) if form.errors: if request.is_ajax(): return JsonResponse({'errors': form.errors}) else: return render_to_response_context( request, 'offers/browse_offers.html', {'form': form, 'offers': []}) else: if userprofile and userprofile.location: lng, lat = userprofile.location.coords location_source = 'userprofile' else: g = GeoIP() ip = request.META.get('REMOTE_ADDR') lat, lng = 52.63639666, 1.29432678223 location_source = 'none' if ip: latlon = g.lat_lon(ip) if latlon: lat, lng = latlon location_source = 'ip' form = OfferBrowseForm(initial={'max_distance': 25, 'latitude': lat, 'longitude': lng, 'location_source': location_source}) offers = [] paginator = Paginator(offers, OFFERS_PER_PAGE) page = paginator.page(request.GET.get('page', 1)) saved_filters = SavedFilter.objects.filter(owner=userprofile) return render_to_response_context(request, 'offers/browse_offers.html', {'form': form, 'page': page, 'saved_filters':saved_filters})
def test03_country(self): "Testing GeoIP country querying methods." g = GeoIP(city='<foo>') fqdn = 'www.google.com' addr = '12.215.42.19' for query in (fqdn, addr): 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))
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') addr = '130.80.29.3' fqdn = 'chron.com' 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.failIf(not isinstance(geom, GEOSGeometry)) lon, lat = (-95.3670, 29.7523) 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 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 home(request): _dict = {} g = GeoIP() # lat, lng = g.lat_lon(get_client_ip(request)) lat, lng = g.lat_lon("108.34.252.180") _dict["lat"] = lat _dict["lng"] = lng point = Point(x=lng, y=lat, srid=4326) nearby_courses = Course.objects.distance(point).order_by("distance")[:15] _dict["nearby_courses"] = nearby_courses nearby_courses_coords = [{"lat": c.location.y, "lng": c.location.x} for c in nearby_courses] _dict["nearby_courses_coords"] = simplejson.dumps(nearby_courses_coords) return render_to_response("home.html", _dict, context_instance=RequestContext(request))
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country='<foo>') addr = '130.80.29.3' fqdn = 'chron.com' 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.failIf(not isinstance(geom, GEOSGeometry)) lon, lat = (-95.3670, 29.7523) 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 __init__(self): if getattr(settings, 'IS_DEV_SERVER', False ) or 'django.contrib.sites' not in settings.INSTALLED_APPS: raise MiddlewareNotUsed() try: from django.contrib.gis.utils import GeoIP, GeoIPException self.g = GeoIP() self.redirect_sites = dict(settings.SITE_GEOIP_REDIRECT) except (ImportError, GeoIPException, ValueError, TypeError, AttributeError): raise ImproperlyConfigured( "The GeoIPRedirectMiddleware requires the" " setting SITE_GEOIP_REDIRECT and GEOIP_PATH to be defined" " along with a working GeoIP installation." " Please see 'django.contrib.gis.utils.geoip.py'.") self.srs_url_re = re.compile("^/siteinfo/srs/?$") self.srs_getvarname = getattr(settings, 'SITE_GEOIP_REDIRECT_GETVARNAME', 'srs')
def lat_lon(self): """ this method returns lat, lon if avail. OR it sets lat and lon from GeoIP and then returns them """ if self.lat and self.lon: return self.lat, self.lon else: g = GeoIP() ret = g.lat_lon(self.ip) if ret: lat, lon = ret self.lat = lat self.lon = lon self.save() return self.lat, self.lon else: return None
def test02_bad_query(self): "Testing GeoIP query parameter checking." cntry_g = GeoIP(city='<foo>') # No city database available, these calls should fail. self.assertRaises(GeoIPException, cntry_g.city, 'google.com') self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com') # Non-string query should raise TypeError self.assertRaises(TypeError, cntry_g.country_code, 17) self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
def __init__(self, *args, **kwargs): if "request" in kwargs: self.request = kwargs["request"] del kwargs["request"] super(UserRegisterForm, self).__init__(*args, **kwargs) if "username" in self.base_fields: del self.base_fields["username"] del self.fields["username"] if hasattr(self, "request"): from django.contrib.gis.utils import GeoIP geoip = GeoIP() iso_city = (geoip.city(self.request.META.get("REMOTE_ADDR", "127.0.0.1")) or {}).get("city") city = get_object_or_None(City, iso__iexact=iso_city or "") if city: self.fields["city"].initial = city.pk
def find_location(self, ip): """ Pass in a dotted quad. first try the GeoIP db. If not there, fails to the db. This also catches the error in api is installed but settings not correct. """ ret_dict = {} try: g = GeoIP() # g = GeoIP() geolocation = g.city(ip) ret_dict["latitude"] = str(geolocation["latitude"]) ret_dict["longitude"] = str(geolocation["longitude"]) ret_dict["country_code"] = geolocation["country_code"] ret_dict["region"] = geolocation["region"] ret_dict["city"] = geolocation["city"] return ret_dict except: # didn't work so fall back to the db # print "Unexpected error:", sys.exc_info() try: lip = ip_to_long(ip) ret = Blocks.objects.filter(start__lte=lip).filter(end__gte=lip)[0] ret_dict["latitude"] = ret.loc.latitude ret_dict["longitude"] = ret.loc.longitude ret_dict["country_code"] = ret.loc.country ret_dict["region"] = ret.loc.region ret_dict["city"] = ret.loc.city ret_dict["postal_code"] = ret.loc.postal_code ret_dict["metro_code"] = ret.loc.metro_code ret_dict["area_code"] = ret.loc.area_code return ret_dict except: """ Danger Will Robinson !!!! Just bail. """ ret_dict["latitude"] = "25.0392" ret_dict["longitude"] = "121.5250" ret_dict["country_code"] = "TW" ret_dict["region"] = "03" ret_dict["city"] = "Taipei" return ret_dict
def _get_geoip_data(self): """ Attempts to retrieve MaxMind GeoIP data based upon the visitor's IP """ if not HAS_GEOIP or not USE_GEOIP: # go no further when we don't need to log.debug('Bailing out. HAS_GEOIP: %s; TRACKING_USE_GEOIP: %s' % (HAS_GEOIP, USE_GEOIP)) return None if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=CACHE_TYPE) self._geoip_data = gip.city(self.ip_address) except GeoIPException: # don't even bother... log.error('Error getting GeoIP data for IP "%s": %s' % (self.ip_address, traceback.format_exc())) return self._geoip_data
def set_redirect_by_ip(self, request): g = GeoIP() ip = get_real_ip(request) user_city = g.city(ip) target_city = None if user_city: target_city = get_object_or_None(City, name_by_geoip=user_city['city']) if not target_city: target_city = City.objects.get(is_default=True) target_domain = target_city.site.domain if not target_city.site.domain.startswith('http'): target_domain = 'http://%s' % target_domain target_url = urlparse(target_domain) request_url = urlparse('http://%s/' % request.get_host()) if not target_url.netloc == request_url.netloc: self.redirect_to = target_city.site.domain
def parse_data(self): self.parse_useragent() if self.ip: try: g = GeoIP() location = g.city(self.ip) if location: country = ox.get_country_name(location['country_code']) if location['city']: city = location['city'] if type(city) != unicode: city = city.decode('latin-1') self.location = u'%s, %s' % (city, country) self.location_sort = u'%s, %s' % (country, city) else: self.location_sort = self.location = country else: self.location_sort = self.location = None except: self.location_sort = self.location = None pass
def checkin(request): ip = request.META['REMOTE_ADDR'] geoip = GeoIP() coords = geoip.coords(ip) if not coords: coords = (0, 0) if request.method == "POST": form = CheckinForm(request.POST) if form.is_valid(): checkin = form.save(commit=False) checkin.type = '1' checkin.geodata = Point(coords) checkin.save() if request.is_ajax(): return HttpResponse("{response: 'ok'}", mimetype="application/json") else: HttpResponseRedirect('/') else: form = CheckinForm() return render_to_response('checkin.html', {'form':form}, RequestContext(request))
def test04_city(self): "Testing GeoIP city querying methods." g = GeoIP(country="<foo>") addr = "130.80.29.3" fqdn = "chron.com" 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.failIf(not isinstance(geom, GEOSGeometry)) lon, lat = (-95.4152, 29.7755) 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 wrapper(*args, **kw): request = args[0] user = request.user org = Organization.objects.get(org_id=user.get_profile().org_id) try: country_code = GeoIP().country_code( request.META.get('REMOTE_ADDR')) except Exception as e: logger.exception("Error resolving country from IP : \n%s" % e) raise if country_code is None or org.country.code == country_code: return f(*args, **kw) return HttpResponse(status=401)
def get_country_by_ip(ip): from api.views import create_dump_file g = GeoIP() country = None try: name = g.country(ip)['country_name'] if name == 'Russian Federation': name = 'Russia' elif name == 'United States': name = 'USA' elif name == 'Moldova, Republic of': name = 'Moldova' elif name == 'United Kingdom': name = 'UK' elif name == 'Iran, Islamic Republic of': name = 'Iran' try: country = Country.objects.get(name_en=name) except Country.DoesNotExist: pass ''' if name: with open('%s/dump_geoip_nof_country.xml' % settings.NOF_DUMP_PATH, 'r') as f: xml_data = BeautifulSoup(f.read(), from_encoding="utf-8") name_slug = low(del_separator(name)) countries_slugs = [i.get('slug') for i in xml_data.findAll('country')] data_nof_country = '' if name_slug not in countries_slugs: data_nof_country = '<country name="%s" slug="%s"></country>' % (name, name_slug) xml_data = str(xml_data).replace('<html><head></head><body><data>','').replace('</data></body></html>','') xml_data = '<data>%s%s</data>' % (xml_data, data_nof_country) create_dump_file('geoip_nof_country', settings.NOF_DUMP_PATH, xml_data) ''' except TypeError: pass return country
def detect_currency(request): country = GeoIP().country(request.META['REMOTE_ADDR']) currency_id = Currency.objects.get(symbol='EUR').id if country['country_name']: country_up = country['country_name'].upper() if country_up in COUNTRY_CURRENCY_MAP: symbol = COUNTRY_CURRENCY_MAP[country_up] try: currency = Currency.objects.get(symbol=symbol) currency_id = currency.id except ObjectDoesNotExist: pass return currency_id
def wrapper(*args, **kw): request = args[0] user = request.user org = Organization.objects.get(org_id=user.get_profile().org_id) try: country_code = GeoIP().country_code( request.META.get('REMOTE_ADDR')) except Exception as e: logger.exception("Error resolving country from IP : \n%s" % e) raise log_message = 'User: %s, IP: %s resolved in %s, for Oragnization id: %s located in country: %s ' %\ (user, request.META.get('REMOTE_ADDR'), country_code, org.org_id, org.country) logger.info(log_message) return f(*args, **kw)
def process_request(self, request): from django.conf import settings from meegloo.international.models import Country try: from django.contrib.gis.utils import GeoIP except ImportError: request.country = Country.objects.get( pk=getattr(settings, 'COUNTRY_ID')) return g = GeoIP() ip = request.META.get( 'HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_IP', request.META.get('REMOTE_ADDR'))) if ip != '127.0.0.1': d = g.country(ip) code = d['country_code'] request.country = Country.objects.get(code=code) else: pk = getattr(settings, 'COUNTRY_ID') request.country = Country.objects.get(pk=pk)
def dashboard_create(request): if request.method == "POST": form = DashboardForm(request.POST) if form.is_valid(): dashboard = form.save(commit=False) dashboard.user = request.user route_formset = RouteFormSet(request.POST, instance=dashboard) if route_formset.is_valid(): dashboard.save() route_formset.save() messages.success(request, "Created!") return HttpResponseRedirect(dashboard.get_absolute_url()) else: route_formset = RouteFormSet(instance=Dashboard()) else: # try to find the best city match initial = {} if request.user.dashboards.exists(): # Use existing city to start with initial['city'] = request.user.dashboards.all()[0].city else: # try a GeoIP lookup geoip = GeoIP().geos(request.META['REMOTE_ADDR']) if geoip: initial['city'] = City.objects.distance(geoip).order_by( '-distance')[0] form = DashboardForm(initial=initial) route_formset = RouteFormSet(instance=Dashboard()) context = { 'form': form, 'route_formset': route_formset, 'title': 'New Dashboard', 'stopFusionTableId': settings.GTFS_STOP_FUSION_TABLE_ID, 'city_data': json.dumps(City.objects.get_map_info()), } return TemplateResponse(request, "mine/dashboard_form.html", context)
class GeoIPRedirectMiddleware(object): """ GeoIP redirect middleware. If enabled, the middleware determines the visitor's location by checking his REMOTE_ADDR with the GeoIP DB (working GeoIP setup required, see: 'django.contrib.gis.utils.geoip.py'). The determined country code is checked against 'settings.SITE_GEOIP_REDIRECT', which must be a list of 2-tuples with iso country code (see: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) and corresponding site_id. If a matching country_code setting is found, a redirect (302) is issued to the site's domain. Author: Maik LUSTENBERGER, Divio GmbH, 2009 """ def __init__(self): if getattr(settings, 'IS_DEV_SERVER', False ) or 'django.contrib.sites' not in settings.INSTALLED_APPS: raise MiddlewareNotUsed() try: from django.contrib.gis.utils import GeoIP, GeoIPException self.g = GeoIP() self.redirect_sites = dict(settings.SITE_GEOIP_REDIRECT) except (ImportError, GeoIPException, ValueError, TypeError, AttributeError): raise ImproperlyConfigured( "The GeoIPRedirectMiddleware requires the" " setting SITE_GEOIP_REDIRECT and GEOIP_PATH to be defined" " along with a working GeoIP installation." " Please see 'django.contrib.gis.utils.geoip.py'.") self.srs_url_re = re.compile("^/siteinfo/srs/?$") self.srs_getvarname = getattr(settings, 'SITE_GEOIP_REDIRECT_GETVARNAME', 'srs') def process_request(self, request): assert hasattr(request, 'session'), \ "The 'GeoIPRedirectMiddleware' requires the app" \ " 'django.contrib.sessions' to be in INSTALLED_APPS." \ " Also make sure that 'GeoIPRedirectMiddleware' comes" \ " after 'django.contrib.sessions.middleware.SessionMiddleware'" \ " in the setting 'MIDDLEWARE_CLASSES'." site_settings = SiteSettings.objects.get_current() if not site_settings.geoip_redirect: return None if self.srs_url_re.match(request.path): return None if request.GET.get(self.srs_getvarname, False): # Var ?srs=1 is in GET. # Set session key. ATTENTION: This does not work, if a subsequent request middleware does a redirect! request.session['site_redirect_stop'] = True return None if request.session.get('site_redirect_stop', False): # The redirect stop flag has been set by 'siteinfo.views.set_redirect_stop' return None if getattr(settings, 'SITE_GEOIP_REDIRECT_ONCE', True): if request.session.get('site_no_redirect', False): # Redirect info already lives in session. No need for redirect. So no further action. return None if request.COOKIES.get('site_no_redirect', False): # Redirect has already occurred. Write cookie info to session for accurate lifetime. request.session['site_no_redirect'] = True return None if getattr(settings, 'SITE_GEOIP_REDIRECT_ROOT_ONLY', True) and request.get_full_path() != '/': return None # Start with the geo action. ip = request.META.get('REMOTE_ADDR') geo_info = self.g.country(ip) try: country_code = geo_info['country_code'].lower() except (KeyError, AttributeError): return None if country_code in self.redirect_sites: site_id = self.redirect_sites[country_code] try: site = Site.objects.get(pk=site_id) except Site.DoesNotExist: return None host = request.get_host() if site.domain in host: return None if getattr(settings, 'SITE_GEOIP_REDIRECT_TO_FULL_PATH', False): path = request.get_full_path() else: path = '' response = HttpResponseRedirect('%s://%s%s' % ( request.is_secure() and 'https' or 'http', site.domain, path, )) if getattr(settings, 'SITE_GEOIP_REDIRECT_ONCE', True): # Set a cookie for the lifetime of a (new) session, to let subsequent requests know of the redirect. # Also, subsequent requests will write this cookie information to the session for accurate lifetime. response.set_cookie( 'site_no_redirect', '1', max_age=(not settings.SESSION_EXPIRE_AT_BROWSER_CLOSE or None) and settings.SESSION_COOKIE_AGE) return response
def save(self, *args, **kwargs): g = GeoIP() self.coords = g.geos(self.ip_address) super(Hit, self).save(*args, **kwargs)
import re from urlparse import urlparse from django.contrib.gis.utils import GeoIP from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from IPy import IP import dns.resolver import dns.reversename from plugin import PluginMixin from scanner.models import STATUS, RESULT_STATUS, RESULT_GROUP from webscanner.utils.geo import make_map geoip = GeoIP() class PluginDNSmail(PluginMixin): name = unicode(_("Check dns MAIL")) description = unicode(_("Check dns MAIL")) wait_for_download = False def run(self, command): from scanner.models import Results domain = command.test.domain() test = command.test if not command.test.check_mail: return STATUS.success try: