• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pygeoip.GeoIP类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: ip2country

def ip2country(request):
    ip = str(request.REQUEST.get('ip'))
    
    geoip = GeoIP(settings.GEOIP, MEMORY_CACHE)
    c = geoip.country_name_by_addr(ip)
    c+="; "
    whois = os.popen("whois %s 2>&1" % ip)
    file.close
    for ln in whois:
        '''
        inetnum:      134.36.0.0 - 134.36.255.255
        descr:        University of Dundee
        descr:        Dundee DD1 4HN
        descr:        Scotland
        netname:      DUNDEE-UNIV
        descr:        University of Dundee
        country:      GB
        '''
        if ln.startswith("inetnum") or ln.startswith("netname") or ln.startswith("descr"):
            c+=ln.split(":")[1].strip()+"; "
        if ln.startswith("country"):
            c+=ln.split(":")[1].strip()+"."
            break
        if len(c) > 400:
            break
        
    return HttpResponse(c)
开发者ID:sbesson,项目名称:registry,代码行数:27,代码来源:views.py


示例2: get_weather

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,代码行数:33,代码来源:utils.py


示例3: run

    def run(self):
        log.debug("Updating mirror database")
        geoip = GeoIP(Config.GEOIP_PATH_V4)

        for status in mirror_statuses(unofficial_mirrors=Config.UNOFFICIAL_MIRRORS):
            name = status['mirror']
            if name == "a.pypi.python.org":
                # don't include 'a' in the list of mirrors - it's no mirror after all
                continue
            time_diff = status['time_diff']
            if not isinstance(time_diff, timedelta):
                continue

            log.debug("  Processing mirror '%s'", name)
            record = geoip.record_by_name(name)
            lat = record['latitude']
            lon = record['longitude']

            log.debug("    Age: %d, Lat: %0.5f, Lon: %0.5f", time_diff.total_seconds(), lat, lon)

            try:
                mirror = Mirror.objects.get(name=name)
            except ObjectNotFound:
                mirror = Mirror(name=name)
            mirror.age = time_diff.total_seconds()
            mirror.lat = lat
            mirror.lon = lon

            mirror.save()

        self.redis.set(Config.KEY_LAST_UPDATE, time.time())
        log.debug("Finished updating mirror database")
开发者ID:ulope,项目名称:nearest_pypi,代码行数:32,代码来源:update_mirrors.py


示例4: perform

    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,代码行数:35,代码来源:dns_geoip.py


示例5: scanit

	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,代码行数:27,代码来源:DerpletteApp.py


示例6: IPToLocation

def IPToLocation(ipaddr):
    from ooni.settings import config

    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 data directories."
                "Try running ooniresources or"
                " edit your ooniprobe.conf")

    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:
        asn_dat = GeoIP(asn_file)
        location['asn'] = asn_dat.org_by_addr(ipaddr).split(' ')[0]
    except:
        error()

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


示例7: IPToLocation

def IPToLocation(ipaddr):
    from ooni.settings import config

    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'}
    if not asn_file or not country_file:
        log.err("Could not find GeoIP data file in data directories."
                "Try running ooniresources or"
                " edit your ooniprobe.conf")
        return location

    country_dat = GeoIP(country_file)
    asn_dat = GeoIP(asn_file)

    country_code = country_dat.country_code_by_addr(ipaddr)
    if country_code is not None:
        location['countrycode'] =  country_code

    asn = asn_dat.org_by_addr(ipaddr)
    if asn is not None:
        location['asn'] = asn.split(' ')[0]

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


示例8: __init__

 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)
开发者ID:gabber7,项目名称:ip2city,代码行数:9,代码来源:ip2city.py


示例9: IP_by_DataBase

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,代码行数:9,代码来源:webserve.py


示例10: update_data

 def update_data(self, request, commit=True):
     self.user_agent = request.META.get('HTTP_USER_AGENT', None)
     geo = GeoIP(settings.GEOIP_DATABASE)
     self.country_code = geo.country_code_by_addr(
         request.META.get('REMOTE_ADDR', None)
     )
     self.visitor_ip = request.META.get('REMOTE_ADDR', None)
     if hasattr(request, 'user') and request.user.is_authenticated():
         self.visitor = request.user
     if commit:
         self.save()
开发者ID:biznixcn,项目名称:WR,代码行数:11,代码来源:models.py


示例11: ip2city

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,代码行数:54,代码来源:ip2city.py


示例12: add_geo

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,代码行数:11,代码来源:Geo.py


示例13: add_coords_to_edges

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,代码行数:13,代码来源:Geo.py


示例14: process_request

 def process_request(self, request):
     if 'django_timezone' in request.session:
         tzname = request.session['django_timezone']
         timezone.activate(pytz.timezone(tzname))
     else:
         ip = get_real_ip(request)
         if ip is not None:
             gi = GeoIP(settings.GEOIP_DATABASE, MEMORY_CACHE)
             tzname = gi.time_zone_by_addr(ip)
             if tzname is not None:
                 request.session['django_timezone'] = tzname
                 timezone.activate(pytz.timezone(tzname))
             else:
                 timezone.deactivate()
开发者ID:richardcornish,项目名称:richardcornish,代码行数:14,代码来源:middleware.py


示例15: ip_to_country

def ip_to_country(ip_address):
	db = GeoIP(
		path.abspath(
			path.join(
				path.dirname(__file__),
				'fixtures',
				'geoip.dat'
			)
		),
		MEMORY_CACHE
	)
	
	return Country.objects.get(
		code = db.country_code_by_addr(ip_address)
	)
开发者ID:cheekybastard,项目名称:bambu-tools,代码行数:15,代码来源:__init__.py


示例16: GeoIPParser

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,代码行数:30,代码来源:geoip.py


示例17: __init__

 def __init__(self):
     """
     Constructor -
     It starts with some basic initialisations and spawns a coordinator
     thread which creates more threads to perform the master server query 
     and also the status updates for the servers.
     """
     self.serverqueue = Queue()
     self.messageque = Queue()
     self.pulsemessageque = Queue() 
     
     self.threadcount = 0
     self.servercount = 0
     self.processedserver = 0
     self.filterdcount = 0
     
     self.gui_lock = None
     self.geo_lock = None
     
     coord = Thread(target=self.coordinator)
     coord.daemon = True
     coord.start()
     
     dbname = Globals.geoip_dir+ '/GeoIP.dat'
     self.pygeoip = GeoIP(dbname, pygeoip.const.MMAP_CACHE)
     
     self.abort = False
开发者ID:anthonynguyen,项目名称:UrTSB,代码行数:27,代码来源:querymanager.py


示例18: location

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,代码行数:16,代码来源:app.py


示例19: get

    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,代码行数:16,代码来源:views.py


示例20: __init__

    def __init__(self, packets, layer=3, geo_ip=os.path.expanduser('~/GeoIP.dat')):
        self.graph = DiGraph()
        self.layer = layer
        self.geo_ip = None
        self.data = {}

        try:
            self.geo_ip = GeoIP(geo_ip)
        except:
            logging.warning("could not load GeoIP data")

        if self.layer == 2:
            edges = map(self._layer_2_edge, packets)
        elif self.layer == 3:
            edges = map(self._layer_3_edge, packets)
        elif self.layer == 4:
            edges = map(self._layer_4_edge, packets)
        else:
            raise ValueError("Other layers than 2,3 and 4 are not supported yet!")

        for src, dst, packet in filter(lambda x: not (x is None), edges):
            if src in self.graph and dst in self.graph[src]:
                self.graph[src][dst]['packets'].append(packet)
            else:
                self.graph.add_edge(src, dst, {'packets': [packet]})

        for node in self.graph.nodes():
            self._retrieve_node_info(node)

        for src, dst in self.graph.edges():
            self._retrieve_edge_info(src, dst)
开发者ID:HardlyHaki,项目名称:PcapViz,代码行数:31,代码来源:core.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.ip2long函数代码示例发布时间:2022-05-25
下一篇:
Python geometry.from_wkt函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap