def admin_get_whos_online(request): """ Ajax request. """ # TODO: Check user auth data = { 'anonymous': [], 'hunters': [] } geoip = GeoIP() for anon in list(AnonymousOnline.objects.all()): data['anonymous'].append({ 'user': '******'.format(anon.ip), 'country': geoip.country(str(anon.ip)) if HAS_GEOIP else '', 'url': anon.referer, 'time': str(anon.last_visit) }) for hunter in list(Online.objects.filter(online=True)): data['hunters'].append({ 'user': hunter.user.username, 'url': hunter.referer, 'time': str(hunter.last_visit) }) remove_older() return JsonResponse(data)
def process_response(self, request, response): # Continue for media if request.path.startswith('/media/') \ or request.path.startswith('/admin/') \ or request.path.startswith('/social-auth/'): return response # If we don't have a country at this point, we need to do some ip # checking or assumption if request.country is None: # Get the Geo location of the requests IP geo_ip = GeoIP() country_geo_ip = geo_ip.country(get_client_ip(request)) if country_geo_ip['country_code']: try: request.country = Country.objects.get( code__iexact=country_geo_ip['country_code']) except Country.DoesNotExist: pass # Try and get the default if request.country is None: try: request.country = Country.objects.get(default=True) except Country.DoesNotExist: pass if request.country: return redirect('/{}{}'.format(request.country.code.lower(), request.path)) return response
def get_coordinates(request): lat_lng = '' cookies = request.COOKIES.get('lat_lng') if cookies: if 'expires' in cookies: cookies = cookies.split("expires",1)[0] cookies = cookies.split(',') try: float(cookies[0]) float(cookies[1]) except ValueError: cookies = '' else: g = GeoIP() x_forwarded_for = request.META.get('HTTP_CLIENT_IP') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') lat_lng = g.lat_lon(ip) if cookies and cookies[0] and cookies[1]: latitude = cookies[0] longitude = cookies[1] elif lat_lng: latitude = lat_lng[0] longitude = lat_lng[1] else: latitude = 42.396645 longitude = -71.109388 coordinates = [latitude, longitude] return coordinates
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 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 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 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 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 get_queryset(self): keyword = self.request.GET.get('q') platform = self.request.GET.get('platform') coord = self.request.GET.get('coord') radius = self.request.GET.get('radius') or 3000 location_str = self.request.GET.get('location') if keyword: positions = models.Position.objects.filter(name__icontains=keyword) else: positions = models.Position.objects.all() if coord: x, y = coord.split(',') coord = fromstr('POINT(%s %s)' % (x, y)) elif location_str: location = models.Location() coord = location.get_point(location_str) else: g = GeoIP() coord = g.geos(self.request.META['HTTP_X_REAL_IP']) if platform: platforms = models.Platform.objects.filter(name=platform) else: platforms = models.Platform.objects.all() locations = models.Location.objects.filter(point__distance_lte=(coord, D(km=radius))) jobs = models.Job.objects.filter(position__in=positions, location__in=locations, platform__in=platforms) if keyword: crawler.search(keyword, location_str) return jobs
def book_details(request, book_id): book = get_object_or_404(Book, id=book_id) context = { 'book': book, } geo_info = GeoIP().city(request.META.get('REMOTE_ADDR')) if not geo_info: geo_info = GeoIP().city("192.206.151.131") context['geo_info'] = geo_info if request.user.is_authenticated(): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): new_review = Review.objects.create( user=request.user, book=context['book'], text=form.cleaned_data.get('text'), latitude=geo_info['latitude'], longitude=geo_info['longitude'], ) new_review.save() else: if Review.objects.filter(user=request.user,book=context['book']).count() == 0: form = ReviewForm() context['form'] = form context['reviews'] = book.review_set.all() return render(request, 'store/detail.html', context)
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 get_queryset(self): ip_address = self.request.META.get('REMOTE_ADDR', None) try: gi = GeoIP(settings.STATIC_ROOT) location = gi.lon_lat(ip_address) except GeoIPException: location = None object_list = [] for form_name, form_model in get_form_models( for_user=self.request.user): try: # first closest objects object_list += list( form_model.objects.distance( Point(location), field_name=form_model.location_field()).order_by( 'distance')[:self.max_objects]) except (TypeError, AttributeError): # falling back to just first objects object_list += list( form_model.objects.order_by('created_at') [:self.max_objects]) return object_list
def get_country_info(request): if not 'geoip' in request.session: g = GeoIP() ip = get_ip_address(request) country_info = g.country(ip) if settings.DEBUG: country_info = g.country('baidu.cn') if country_info['country_name'] == None or country_info[ 'country_code'] == None: country_info = { 'country_name': '', 'country_code': '', 'country_alt_name': '' } JOB_COUNTRIES = getattr(settings, 'JOB_COUNTRIES', []) cc = country_info.get('country_code', '') if cc and cc.upper() in JOB_COUNTRIES: country_info['country_alt_name'] = JOB_COUNTRIES[cc.upper()] else: country_info['country_alt_name'] = country_info.get( 'country_name', '') request.session['country_info'] = country_info request.session['geoip'] = True else: country_info = request.session['country_info'] return country_info
def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PhoneNumberForm(request.POST) # check whether it's valid: try: if form.is_valid(): # process the data in form.cleaned_data as required # ... g = GeoIP() ip = get_client_ip(request) if ip: country = g.country(ip)['country_code'] else: country = 'Rome' # default city origin_number =country_to_origin_number(country) NumPair = AddNumberAndGetPair(form.get_number()) if NumPair.ready == True: c= call(NumPair.Number1,origin_number) c= call(NumPair.Number2,origin_number) UpdateConferenceSerial() # redirect to a new URL: c = None return conf(c,country) except ValidationErr,e: pass
def get_lat_and_long(ip): """ Get the values of the latitude and long by ip address """ g = GeoIP(cache=GeoIP.GEOIP_MEMORY_CACHE) return g.lat_lon(str(ip))#lat, long
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 geojson_amap(request): from django.contrib.gis.measure import Distance from django.contrib.gis.geoip import GeoIP from django.contrib.gis.geos import fromstr if request.GET.get('distance'): dist = request.GET['distance'] else: dist = 20 if request.GET.get('center'): print request.GET['center'] coords = request.GET['center'].split(',') my_lat = coords[0] my_long = coords[1] center = fromstr('POINT(' + my_lat + " " + my_long + ')') else: g = GeoIP(path=settings.PROJECT_PATH + '/config/GEO/') center = g.geos(request.META['REMOTE_ADDR']) region = default_region() if not center or not region.polygon.contains(center): center = region.default_location.point dist = 1000 res = [] for location in Location.objects.filter(point__distance_lte=(center, Distance(km=dist))): for loc in location.located_set.all(): obj = loc.content_object if obj.__class__ == Organization and "amap" in [x.slug for x in obj.category.all()]: res.extend(obj.pref_geoJson()) result = {"type": "FeatureCollection", "features": res} return HttpResponse(json.dumps(result), mimetype="application/json")
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 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 Code Python github API syntax. for g in (g1, g2, g3): self.assertTrue(g._country) self.assertTrue(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.assertIsNone(g4._country) g5 = GeoIP(cntry, city='') self.assertIsNone(g5._city) # Improper parameters. bad_params = (23, 'foo', 15.23) for bad in bad_params: self.assertRaises(GeoIPException, GeoIP, cache=bad) if isinstance(bad, six.string_types): e = GeoIPException else: e = TypeError self.assertRaises(e, GeoIP, bad, 0)
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 home(request): # get Point from request IP address message = request.session.pop('message', None) g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: point = g.geos(ip) # if ip can't be mapped to location (e.g. 127.0.0.*), use default camp randall if not point: point = Point(-89.411784,43.069817) else: point = Point(-89.411784,43.069817) # translate point to city name locator = GoogleV3() location = locator.reverse((point.coords[1], point.coords[0]), exactly_one=True) if not location: city = "Madison" state = "WI" else: address = location.address.split(',') try: city = address[1].strip() state = address[2].strip().split(' ')[0] except IndexError: city = "Madison" state = "WI" context = { 'location' : "{}, {}".format(city, state), "message": message } return render(request, 'home.html', context)
def country_ip(ip): if not ip: return '' geoip = GeoIP() c_code = geoip.country_code(ip) return c_code if c_code else ''
def china_base_url(request): if settings.STAGING: return { 'api_url': 'https://drawquestapi1.com/api/', 'search_url': 'https://searchapi.example.com/', 'web_url': 'https://drawquestapi1.com/', 'rt_url': 'https://rt.example.com/rt', } else: from django.contrib.gis.geoip import GeoIP g = GeoIP() ip = request.META['REMOTE_ADDR'] if ip and g.country_code(ip).upper() == 'CN': return { 'api_url': 'https://drawquestapi1.com/api/', 'search_url': 'https://searchapi.example.com/', 'web_url': 'https://drawquestapi1.com/', 'rt_url': 'https://rt.example.com/rt', } else: return { 'api_url': 'https://api.example.com/', 'search_url': 'https://searchapi.example.com/', 'web_url': 'https://example.com/', 'rt_url': 'https://rt.example.com/rt', }
def post(self, request, *args, **kwargs): if request.user.is_authenticated: return HttpResponseRedirect('/') form = self.form_class(request.POST) if form.is_valid(): if Email.objects.filter(email=form.data['email']).exists(): return render(request, self.template_name, { 'form': self.form_class, 'errors': "Email Already Exist!" }) email = Email.objects.create(email=form.data['email']) user = User.objects.create(email=form.data['email'], name=form.data['name'], primary_email=email) user.set_password(form.data['password']) user.emails.add(email) g = GeoIP() ip = self.get_client_ip(request) user.location = g.country(ip)['country_code'] user.save() user = authenticate(email=form.data['email'], password=form.data['password']) login(request, user) return HttpResponseRedirect('/') return render(request, self.template_name, {'form': form})
def home(request): # get Point from request IP address message = request.session.pop('message', None) g = GeoIP() ip = request.META.get('REMOTE_ADDR', None) if ip: point = g.geos(ip) # if ip can't be mapped to location (e.g. 127.0.0.*), use default camp randall if not point: point = Point(-89.411784, 43.069817) else: point = Point(-89.411784, 43.069817) # translate point to city name locator = GoogleV3() location = locator.reverse((point.coords[1], point.coords[0]), exactly_one=True) if not location: city = "Madison" state = "WI" else: address = location.address.split(',') try: city = address[1].strip() state = address[2].strip().split(' ')[0] except IndexError: city = "Madison" state = "WI" context = {'location': "{}, {}".format(city, state), "message": message} return render(request, 'home.html', context)
def do311(self, irc, msg): nick = msg.args[1] if not nick.startswith('[YOG]') or nick in self.registryValue('nowelcome').split(' '): return realname = msg.args[5] hostname = self._users.pop(nick) try: version = 'Glob2 version %s' % realname.split('-')[1] except: version = 'unknown version' g = GeoIP() country = g.country(hostname)['country_name'] if country == 'France': irc.queueMsg(ircmsgs.privmsg(nick, ('Bonjour %s, bienvenue dans le ' 'salon de jeu Globulation2 en ligne. Il y a actuellement %i ' 'personnes connectées via IRC, elles pourraient se réveiller et ' 'jouer avec vous. Attendez ici au moins quelques minutes, ' 'quelqu\'un pourrait se connecter d\'ici là.') % (nick, len(irc.state.channels['#glob2'].users)))) else: irc.queueMsg(ircmsgs.privmsg(nick, ('Hi %s, welcome to the ' 'globulation online game room. There are currently %i ' 'people connected via IRC, they may awaken and challenge ' 'you to a game. Please stay here at least a few minutes, ' 'someone may connect in the meantime.') % (nick, len(irc.state.channels['#glob2'].users)))) irc.queueMsg(ircmsgs.privmsg('#glob2', ('Welcome to %s, running %s ' 'and connecting from %s.') % (nick, version, country)))
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 home_location(): g = GeoIP() ip = get_ip_address("wlp8s0") location = g.city(ip) if location is not None: location["charset"] = ip return location
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 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 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_loc(request): g = GeoIP() city = g.city(get_client_ip(request)) province = None if city: province = city['region'] return province
def checkin(request): g = GeoIP() userip = get_client_ip(request) mycounrty = g.country(userip) cc = mycounrty["country_name"] return render_to_response("checkin.html" , locals())
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 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 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 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 book_details(request, book_id): book = get_object_or_404(Book, id=book_id) context = { 'book': book, } geo_info = GeoIP().city(request.META.get('REMOTE_ADDR')) if not geo_info: geo_info = GeoIP().city("46.150.193.23") context['geo_info'] = geo_info if request.user.is_authenticated(): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): new_review = Review.objects.create( user=request.user, book=context['book'], text=form.cleaned_data.get('text'), latitude=geo_info['latitude'], longitude=geo_info['longitude']) new_review.save() if Review.objects.filter(user=request.user).count() < 6: subject = "Your MysteryBooks.com discount code is here!" from_email = "*****@*****.**" to_email = [request.user.email] email_context = Context({ 'username': request.user.username, 'code': ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(6)), 'discount': 10 }) text_email = render_to_string('email/review_email.txt', email_context) html_email = render_to_string('email/review_email.html', email_context) msg = EmailMultiAlternatives(subject, text_email, from_email, to_email) msg.attach_alternative(html_email, 'text/html') msg.content_subtype = 'html' msg.send() else: if Review.objects.filter(user=request.user, book=context['book']).count() == 0: form = ReviewForm() context['form'] = form context['reviews'] = book.review_set.all() geo_info = GeoIP().city(request.META.get('REMOTE_ADDR')) if not geo_info: geo_info = GeoIP().city("46.150.193.23") context['geo_info'] = geo_info return render(request, 'store/detail.html', context)
def ip_address_from_request(request): """ get the ip address from the request added special logic for lots of different conditions, proxies, etc. """ meta = request.META # figure out the IP if 'HTTP_TRUE_CLIENT_IP' in meta: # Akamai's Site accelorator's proxy header for real IP ip_address = meta.get('HTTP_TRUE_CLIENT_IP', '') elif 'REMOTE_ADDR' in meta and meta.get('REMOTE_ADDR', '') not in VISITOR_IGNORE_IP_LIST: # use the remote address unless it is one of the ones in the ignore list # then keep looking to see if we find a better one. ip_address = meta.get('REMOTE_ADDR', '') elif 'HTTP_X_REAL_IP' in meta: ip_address = meta.get('HTTP_X_REAL_IP', '') elif 'HTTP_X_FORWARDED_FOR' in meta: forwarded_list = meta.get('HTTP_X_FORWARDED_FOR', '') # forwarded for can have multiple IP's comma seperated # the newest is far left, oldest appended to the right # X-Forwarded-For: client1, proxy1, proxy2 # # http://en.wikipedia.org/wiki/X-Forwarded-For # we want the first one since this is the client ip_address = forwarded_list.split(",")[0] else: ip_address = meta.get('REMOTE_ADDR', None) print ip_address g = GeoIP() country = g.country_name(ip_address) print country return ip_address
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 getPlacesAround(request): 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='147.102.1.1' #test IP for localhost requests. Remove on deployment if ip and (ip!='127.0.0.1'): lat,lng=g.lat_lon(ip) places=[] #places=queryHandlers.OpeniCall() #placesAround=places.getPlaces(city["city"],'foursquare') if request.session.get('4sq-token'): access = request.session.get('4sq-token') places=queryHandlers.FoursquareCall(access_token=access) placesAround=places.getPlacesAround(lat,lng) else: placesAround=[] #print placesAround args = { "places":placesAround, "user":request.user} args.update(csrf(request)) return render_to_response('places.html' , args)
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 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 RegisterUser(request): auth_basic_form = SignupFormOnlyEmail() if request.method == 'POST': user_form = SignupFormOnlyEmail(request.POST) if user_form.is_valid(): try: user = User.objects.get(email__iexact=request.POST['email']) except Exception as e: if 'does not exist' in str(e): user = user_form.save() user_auth = authenticate(identification=user.email, check_password=False) if user_auth is not None: login(request, user_auth) 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') g = GeoIP() lat, lon = g.lat_lon(ip) #lat,lon = g.lat_lon('186.83.0.68') UserProfile.objects.filter(user=user).update( coords='POINT(' + str(lon) + ' ' + str(lat) + ')') request.session['register'] = True return redirect("/change_user/") else: login_form = AuthenticationForm() diccionary = { 'messageReg': 'User already exists', 'login': login_form, 'auth_basic': auth_basic_form, } return render(request, "login.html", diccionary) else: login_form = AuthenticationForm() diccionary = { 'messageReg': 'User already exists', 'login': login_form, 'auth_basic': auth_basic_form, } return render(request, "login.html", diccionary) else: message = 'Invalid data. Please use different information to register' if 'email' in user_form.errors: message = user_form.errors['email'] login_form = AuthenticationForm() login_form.fields['identification'].label = 'Email' diccionary = { 'messageReg': message, 'login': login_form, 'auth_basic': auth_basic_form, } return render(request, "login.html", diccionary) else: return redirect("/login/")
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 get_timezone_from_ip(ip): data = GeoIP().city(ip) or None _timezone = pytz.timezone(timezone.get_current_timezone_name()) if data: _timezone = GeoIPC.time_zone_by_country_and_region( data.get('country_code'), data.get('region')) _timezone = pytz.timezone(_timezone) return _timezone.zone
def geo_ip_to_country(ip): try: from django.contrib.gis.geoip import GeoIP if isinstance(ip, (int, long)): return GeoIP().country(convert.int_to_ip(ip))['country_code'] or 'ZZ' else: return GeoIP().country(ip)['country_code'] or 'ZZ' except: logging.exception('geo_ip_to_country_exception') return 'ZZ'
def country_blocked(request): if settings.ENV == settings.ENV_LOCAL: return False ip_address = get_client_ip(request) g = GeoIP() return g.country(ip_address)['country_code'] in settings.COUNTRY_BLACKLIST
def get_by_ip(self, ip): if settings.DEBUG and ip == "127.0.0.1": # Return a random country for debug purposes return self.get_queryset().order_by("?")[0] g = GeoIP() country_code = g.country_code(ip) if country_code is None: return country = self.get_queryset().filter(code=country_code) if country: return country[0]
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 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 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 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