thein lwin
0
Q:

python pygeoip example

from flask import Flask, request, jsonify
import pygeoip, json

app = Flask(__name__)

geo = pygeoip.GeoIP('GeoLiteCity.dat', pygeoip.MEMORY_CACHE)

@app.route('/')
def index():
    client_ip = request.remote_addr
    geo_data = geo.record_by_addr(client_ip)
    return json.dumps(geo_data, indent=2) + '\n'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=False)
1
def geoip(inp):
    "geoip <host/ip> -- Gets the location of <host/ip>"
    try:
        record = geo.record_by_name(inp)
    except:
        return "Sorry, I can't locate that in my database."

    data = {}

    if "region_name" in record:
        # we try catching an exception here because the region DB is missing a few areas
        # it's a lazy patch, but it should do the job
        try:
            data["region"] = ", " + regions[record["country_code"]][record["region_name"]]
        except:
            data["region"] = ""
    else:
        data["region"] = ""

    data["cc"] = record["country_code"] or "N/A"
    data["country"] = record["country_name"] or "Unknown"
    data["city"] = record["city"] or "Unknown"
    return formatting.output('GeoIP', ['\x02Country:\x02 {country} ({cc}) \x02City:\x02 {city}{region}'.format(**data)]) 
1
def process_request(self, request):
        """
        Identify the country by IP address.

        Store country code in session.
        """
        new_ip_address = get_real_ip(request)
        old_ip_address = request.session.get('ip_address', None)

        if not new_ip_address and old_ip_address:
            del request.session['ip_address']
            del request.session['country_code']
        elif new_ip_address != old_ip_address:
            if new_ip_address.find(':') >= 0:
                country_code = pygeoip.GeoIP(settings.GEOIPV6_PATH).country_code_by_addr(new_ip_address)
            else:
                country_code = pygeoip.GeoIP(settings.GEOIP_PATH).country_code_by_addr(new_ip_address)
            request.session['country_code'] = country_code
            request.session['ip_address'] = new_ip_address
            log.debug('Country code for IP: %s is set to %s', new_ip_address, country_code) 
0
def load_geoip():
    import pygeoip
    from pygeoip.const import MEMORY_CACHE
    
    resource_package = __name__
    filename = pkg_resources.resource_filename(resource_package, 'GeoIP.dat')
    return pygeoip.GeoIP(filename, flags=MEMORY_CACHE) 
0
>>> gi = pygeoip.GeoIP('GeoIPCity.dat')
>>> gi.record_by_addr('64.233.161.99')
{
    'city': u'Mountain View',
    'region_code': u'CA',
    'area_code': 650,
    'time_zone': 'America/Los_Angeles',
    'dma_code': 807,
    'metro_code': 'San Francisco, CA',
    'country_code3': 'USA',
    'latitude': 37.41919999999999,
    'postal_code': u'94043',
    'longitude': -122.0574,
    'country_code': 'US',
    'country_name': 'United States',
    'continent': 'NA'
}
>>> gi.time_zone_by_addr('64.233.161.99')
'America/Los_Angeles'
0
$ wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
$ gunzip GeoLiteCity.dat.gz
0
pip install pygeoip
0
def _country_code_from_ip(ip_addr):
    """
    Return the country code associated with an IP address.
    Handles both IPv4 and IPv6 addresses.

    Args:
        ip_addr (str): The IP address to look up.

    Returns:
        str: A 2-letter country code.

    """
    if ip_addr.find(':') >= 0:
        return pygeoip.GeoIP(settings.GEOIPV6_PATH).country_code_by_addr(ip_addr)
    else:
        return pygeoip.GeoIP(settings.GEOIP_PATH).country_code_by_addr(ip_addr) 
0
>>> gi = pygeoip.GeoIP('GeoIPRegion.dat')
>>> gi.region_by_name('apple.com')
{'region_code': 'CA', 'country_code': 'US'}
0
def count_ref_ipPerAsn(ref=None):

    gi = pygeoip.GeoIP("../lib/GeoIPASNum.dat")
    
    if ref is None:
        ref = pickle.load(open("./saved_references/56d9b1eab0ab021d00224ca8_routeChange.pickle","r"))

    ipPerAsn = defaultdict(set)

    for targetRef in ref.values(): 
        for router, hops in targetRef.iteritems():
            for hop in hops.keys():
                if hop != "stats":
                    ipPerAsn[asn_by_addr(hop,gi)[0]].add(hop)

    return ipPerAsn 
0

New to Communities?

Join the community