当前位置: 首页>>代码示例>>Python>>正文


Python GeoIP.record_by_addr方法代码示例

本文整理汇总了Python中pygeoip.GeoIP.record_by_addr方法的典型用法代码示例。如果您正苦于以下问题:Python GeoIP.record_by_addr方法的具体用法?Python GeoIP.record_by_addr怎么用?Python GeoIP.record_by_addr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygeoip.GeoIP的用法示例。


在下文中一共展示了GeoIP.record_by_addr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ip2city

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
class ip2city(object):

    stats = {
        'requests': 0,
        'successes': 0,
        'errors': 0,
    }

    geoip_v4 = None
    geoip_v6 = None


    def __init__(self, database, database_v6):
        self.url_map = Map([
            Rule('/', endpoint='resolve'),
            Rule('/favicon.ico', endpoint='favicon'),
            Rule('/status', endpoint='status'),
        ])
        self.geoip_v4 = GeoIP(database, MEMORY_CACHE)
        if database_v6:
            self.geoip_v6 = GeoIP(database_v6, MEMORY_CACHE)


    # Serve empty favicon.ico
    def on_favicon(self, request):
        return Response()


    def on_status(self, request):
        response = self.stats
        response['status'] = 'Working for you.'
        return Response(json.dumps(response))


    def on_resolve(self, request):
        ip = request.args.get('ip')
        self.stats['requests'] += 1
        record = {}

        try:
            if ':' in ip:
                if self.geoip_v6:
                    record = self.geoip_v6.record_by_addr(ip)
                    self.stats['successes'] += 1
                else:
                    self.stats['errors'] += 1
            else:
                record = self.geoip_v4.record_by_addr(ip)
                self.stats['successes'] += 1
        except GeoIPError, e:
            print e
            self.stats['errors'] += 1

        return Response(json.dumps(record))
开发者ID:gabber7,项目名称:ip2city,代码行数:56,代码来源:ip2city.py

示例2: IPToLocation

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def IPToLocation(ipaddr):
    from ooni.settings import config

    city_file = os.path.join(config.advanced.geoip_data_dir, 'GeoLiteCity.dat')
    country_file = os.path.join(config.advanced.geoip_data_dir, 'GeoIP.dat')
    asn_file = os.path.join(config.advanced.geoip_data_dir, 'GeoIPASNum.dat')

    location = {'city': None, 'countrycode': 'ZZ', 'asn': 'AS0'}
    
    try:
        country_dat = GeoIP(country_file)
        location['countrycode'] = country_dat.country_code_by_addr(ipaddr)
        if not location['countrycode']:
            location['countrycode'] = 'ZZ'
    except IOError:
        log.err("Could not find GeoIP data file. Go into %s "
                "and make sure GeoIP.dat is present or change the location "
                "in the config file" % config.advanced.geoip_data_dir)
    try:
        city_dat = GeoIP(city_file)
        location['city'] = city_dat.record_by_addr(ipaddr)['city']
    except:
         log.err("Could not find the city your IP is from. "
                "Download the GeoLiteCity.dat file into the geoip_data_dir"
                " or install geoip-database-contrib.")
    try:
        asn_dat = GeoIP(asn_file)
        location['asn'] = asn_dat.org_by_addr(ipaddr).split(' ')[0]
    except:
        log.err("Could not find the ASN for your IP. "
                "Download the GeoIPASNum.dat file into the geoip_data_dir"
                " or install geoip-database-contrib.")
    
    return location
开发者ID:GarysRefererence2014,项目名称:ooni-probe,代码行数:36,代码来源:geoip.py

示例3: IPToLocation

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def IPToLocation(ipaddr):
    city_file = os.path.join(config.advanced.geoip_data_dir, 'GeoLiteCity.dat')
    country_file = os.path.join(config.advanced.geoip_data_dir, 'GeoIP.dat')
    asn_file = os.path.join(config.advanced.geoip_data_dir, 'GeoIPASNum.dat')

    location = {'city': None, 'countrycode': None, 'asn': None}
    try:
        city_dat = GeoIP(city_file)
        try:
            location['city'] = city_dat.record_by_addr(ipaddr)['city']
        except TypeError:
            location['city'] = None
    
        country_dat = GeoIP(country_file)
        location['countrycode'] = country_dat.country_code_by_addr(ipaddr)
        if not location['countrycode']:
            location['countrycode'] = 'ZZ'

        asn_dat = GeoIP(asn_file)
        try:
            location['asn'] = asn_dat.org_by_addr(ipaddr).split(' ')[0]
        except AttributeError:
            location['asn'] = 'AS0'

    except IOError:
        log.err("Could not find GeoIP data files. Go into %s "
                "and run make geoip or change the geoip_data_dir "
                "in the config file" % config.advanced.geoip_data_dir)
        raise GeoIPDataFilesNotFound
    
    return location
开发者ID:david415,项目名称:ooni-probe,代码行数:33,代码来源:geoip.py

示例4: scanit

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
	def scanit(self): #funtion to scan on record results
		"""
		scans a target, the target is taken from the TK box target
		:return: nothing
		"""
		gic = GeoIP(GEOIP_DATABASE) #change this to the location of GeoLiteCity.dat
		target = self.textbox.get()
		if target != '' and target != 'IP or Hostname': #error checking (not empty string)
			try:
				target_ip = socket.gethostbyname(target) #attempts to get an ip from hostnam/ip passed through 
				gic = GeoIP(GEOIP_DATABASE) #load geoIP database
				addr = gic.record_by_addr(target_ip) #if this works (getting ip) find address of ip
				lat = addr['latitude']
				lng = addr['longitude']
				htmlPath = TARGET_HTML + target_ip + '.html'
				mymap = maps(lat,lng,16) #create google map file
				mymap.addradpoint(lat, lng, 100, "#0000FF")
				mymap.draw(htmlPath)
				# TODO: maybe add this back later...
				# if lng != 0 and lat !=  0:
				#	webbrowser.open(htmlPath)
				self.nmap_scan(target_ip, [lat,lng])
			except socket.gaierror: #if finding IP fails
				print 'ERROR: Counld not get ip from hostname'
			except TypeError:  #if ip has no address (like 127.0.0.1) set lat and lng to 0,0
				# TODO: make more graceful
				print 'Could not get coordinates from GeoIP Database.'
开发者ID:FireElementalNE,项目名称:DERP,代码行数:29,代码来源:DerpletteApp.py

示例5: perform

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
    def perform(self):
        '''
        Main method of the class that perform all actions.

        '''

        # Define list of coordinates
        coords = []
        # Open file for reading
        with open(self.dict_file, "r") as lines:
            try:
                for line in lines.readlines():
                    fulldomain = line.rstrip() + "." + self.domain
                    try:
                        # Get the A target and preference of a name
                        answers = dns.resolver.query(fulldomain, 'A')
                        if type(answers) == dns.resolver.Answer:
                            # Iterate through answers and getting data.
                            for rdata in answers:
                                ip = rdata.address
                                # Create instance of GeoIP class
                                gi = GeoIP(self.dat_file)
                                # Call method record_by_addr
                                go = gi.record_by_addr(ip)
                                # Get latitude and longitude from DNS answer
                                coord = (go['latitude'], go['longitude'])
                                coords.append([fulldomain, coord])
                    except:
                        pass
            # The query name does not exist.
            except (dns.exception.DNSException):
                pass

        # Call method for generate KML file
        self.to_kml(coords)
开发者ID:akalex,项目名称:DevProject,代码行数:37,代码来源:dns_geoip.py

示例6: GeoIPParser

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
class GeoIPParser(ExtractFieldParser):
    '''
    Get geo info from IP address.
    '''
    def __init__(self,
                 field='clientip',
                 out_field='geoip',
                 geoip_dat='',
                 use_hash=True,
                 *args,
                 **kwargs):
        super(GeoIPParser, self).__init__(field, *args, **kwargs)
        self.out_field = out_field
        self.get_loc = _loc_geohash if HAS_GEOHASH and use_hash else _loc_point
        try:
            self.geoip = GeoIP(geoip_dat)
        except (IOError, GeoIPError) as exc:
            self.logger.error('Invalid GeoIP Database file: %s', geoip_dat)
            raise exc

    def parse(self, event):
        ip_addr = self.data
        try:
            geo_info = self.geoip.record_by_addr(ip_addr)
            if 'latitude' in geo_info and 'longitude' in geo_info:
                geo_info['location'] = self.get_loc(geo_info)
            event[self.out_field] = geo_info
        except (IndexError, TypeError):
            self.logger.warn('Failed to get Geo info from ip: %s', ip_addr)
        return event
开发者ID:yalp-log,项目名称:yalp,代码行数:32,代码来源:geoip.py

示例7: IPToLocation

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def IPToLocation(ipaddr):
    from ooni.settings import config

    city_file = config.get_data_file_path('GeoIP/GeoLiteCity.dat')
    country_file = config.get_data_file_path('GeoIP/GeoIP.dat')
    asn_file = config.get_data_file_path('GeoIP/GeoIPASNum.dat')

    location = {'city': None, 'countrycode': 'ZZ', 'asn': 'AS0'}

    def error():
        log.err("Could not find GeoIP data file in %s."
                "Try running ooniresources --update-geoip or"
                " edit your ooniprobe.conf" % config.advanced.geoip_data_dir)

    try:
        country_dat = GeoIP(country_file)
        location['countrycode'] = country_dat.country_code_by_addr(ipaddr)
        if not location['countrycode']:
            location['countrycode'] = 'ZZ'
    except IOError:
        error()

    try:
        city_dat = GeoIP(city_file)
        location['city'] = city_dat.record_by_addr(ipaddr)['city']
    except:
        error()

    try:
        asn_dat = GeoIP(asn_file)
        location['asn'] = asn_dat.org_by_addr(ipaddr).split(' ')[0]
    except:
        error()

    return location
开发者ID:d33tah,项目名称:ooni-probe,代码行数:37,代码来源:geoip.py

示例8: get_weather

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def get_weather(request):
    """Return weather of location from IP address.

    https://pypi.python.org/pypi/django-ipware
    https://pypi.python.org/pypi/pygeoip
    https://pypi.python.org/pypi/python-forecastio
    """
    ip = get_real_ip(request)
    if ip is not None:
        gi = GeoIP(settings.GEOIP_DATABASE, MEMORY_CACHE)
        record = gi.record_by_addr(ip)
        if record is not None:
            try:
                latitude = record['latitude']
                longitude = record['longitude']
            except KeyError:
                return None
            try:
                forecast = forecastio.load_forecast(settings.DARKSKY_API_KEY, latitude, longitude)
                currently = forecast.currently()
            except Exception:
                return None
            return {
                'icon': weather_icons.get(currently.icon, None),
                'summary': currently.summary.lower(),
                'temperature': int(currently.temperature),
                'city': record.get('city', None),
                'country': record.get('country_name', None),
            }
        else:
            return None
    else:
        return None
开发者ID:richardcornish,项目名称:richardcornish,代码行数:35,代码来源:utils.py

示例9: IP_by_DataBase

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def IP_by_DataBase(ip):
    """
        Retorna as iformações de geo posicionamento atraver da base de dados local 
        Disponivel no site http://appliedsec.github.com/pygeoip/
        Data Base http://dev.maxmind.com/geoip/geolite
         
    """
    gi = GeoIP(PATH_GEOIP_CITY)
    return gi.record_by_addr(ip) or {}
开发者ID:cesarbruschetta,项目名称:django-in-gae,代码行数:11,代码来源:webserve.py

示例10: add_geo

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def add_geo(nodes):
  from pygeoip import GeoIP
  gi = GeoIP(GEODB)

  for k,v in nodes.items():
    try:
      nodes[k].update(gi.record_by_addr(v["external-ip"]))
    except Exception as e:
      sys.stderr.write(str(e))
      sys.stderr.write("Cannot determine GeoData for %s\n"%k)
  return nodes
开发者ID:krebscode,项目名称:painload,代码行数:13,代码来源:Geo.py

示例11: add_coords_to_edges

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def add_coords_to_edges(nodes):
  from pygeoip import GeoIP
  gi = GeoIP(GEODB)

  for k,v in nodes.items():
    for i,j in enumerate(v.get("to",[])):
      data=gi.record_by_addr(j["addr"])
      try:
        j["latitude"]=data["latitude"]
        j["longitude"]=data["longitude"]
      except Exception as e: pass

  return nodes
开发者ID:krebscode,项目名称:painload,代码行数:15,代码来源:Geo.py

示例12: get

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
    def get(self, request, *args, **kwargs):
        ip = request.META.get('X-FORWARDED-FOR')
        if not ip:
            ip = request.META['REMOTE_ADDR']


        
        if ip[:3] == "127" or ip[:8] == "168.192." or ip[:10] == "192.168.0.":
            ip = "201.76.161.146"

        
        geo = GeoIP("geoip/GeoLiteCity.dat")
        region = geo.record_by_addr(ip)


        return http.HttpResponse(dumps(region, cls=DjangoJSONEncoder), content_type='application/json')
开发者ID:ecofunds,项目名称:ecofunds-trunk,代码行数:18,代码来源:views.py

示例13: location

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def location():

	callback = request.args.get('callback', False);
	ip = request.args.get('ip', client_ip());
	
	gi = GeoIP('data/GeoLiteCity.dat')
	geodata = gi.record_by_addr(ip);
	geodata['ip_address'] = ip;
	geodata = json.dumps(geodata)

	if callback:
		content = str(callback) + '(' + str(geodata) + ')'
	else:
		content = geodata

 	return current_app.response_class(content, mimetype='application/json')
开发者ID:pendexgabo,项目名称:yet-another-geoip-project,代码行数:18,代码来源:app.py

示例14: __init__

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
 def __init__(self, ip):
     class CityNotDetected(Exception):
         pass
     try:
         # если не удалось определить через ipgeo
         # то определяем через pygeoip
         geo = GeoIP(settings.GEO_CITY_DAT_FILE)
         location = geo.record_by_addr(ip)
         if not location:
             raise CityNotDetected(
                 'не удалось определить через pygeoip'
             )
         city_name = location['city']
         longitude = location['longitude']
         latitude = location['latitude']
         if location['country_name'] == 'Russian Federation':
             try:
                 # определяем положение через ipgeo
                 geo = Range.objects.find(ip)
                 if not geo.location:
                     raise CityNotDetected(
                         'Не удалось определить через ipgeo'
                     )
                 city_name = geo.location.name
                 longitude = geo.location.lon
                 latitude = geo.location.lat
             except (CityNotDetected, Range.DoesNotExist):
                 pass
         self.set_location(
             city=city_name,
             longitude=longitude,
             latitude=latitude,
             timezone=location['time_zone']
         )
     except CityNotDetected:
         # если ничего не определили - считаем что позиция мск
         self.set_location(
             city='Москва',
             longitude=settings.MSK_LONGITUDE,
             latitude=settings.MSK_LATITUDE,
             timezone='Europe/Moscow'
         )
开发者ID:Ravall,项目名称:daodiet,代码行数:44,代码来源:models.py

示例15: events

# 需要导入模块: from pygeoip import GeoIP [as 别名]
# 或者: from pygeoip.GeoIP import record_by_addr [as 别名]
def events(request):
    lat = request.GET.get("lat")
    lon = request.GET.get("lon")
    if not lat or not lon:
        raise Http404

    if request.GET.get("provider"):
        providers = [request.GET.get("provider")]
    else:
        providers = PROVIDERS

    cur_time = int(time.time())

    gi = GeoIP(settings.GEOCITYFILE,pygeoip.STANDARD)
    
    if request.META['REMOTE_ADDR']=='127.0.0.1':
        ip = '64.134.231.43'
    else:
        ip = request.META['REMOTE_ADDR']

    timezone = pytz.timezone(gi.record_by_addr(ip)['time_zone'])
    local_time = timezone.localize(datetime.datetime.now())

    num_results = int(request.GET.get("num_results")) if request.GET.get("num_results") else 10
    offset = int(request.GET.get("offset")) if request.GET.get("offset") else 0

    cache_key = "%s%s" % (int(float(lat)*100)/100.00,int(float(lon)*100)/100.00)
    cached_value = cache.get(cache_key)
    if cached_value:
        return HttpResponse(json.dumps({'results':cached_value[offset*num_results:num_results*(offset+1)]}))
    
    threads = [Greenlet.spawn(provider_request_map[provider],lat,lon,cur_time,local_time,timezone) for provider in providers]

    results = []
    map(results.extend,[g.get() for g in threads])
    results.sort(key = lambda d: d['start_time'])

    cache.set(cache_key,results,60*10)

    return HttpResponse(json.dumps({'results':results[offset*num_results:num_results*(offset+1)]}))
开发者ID:systemizer,项目名称:BatteriesNotIncluded,代码行数:42,代码来源:views.py


注:本文中的pygeoip.GeoIP.record_by_addr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。