What python libraries can tell me approximate location and time zone given an IP address?

后端 未结 13 731
借酒劲吻你
借酒劲吻你 2020-11-28 03:31

Looking to implement better geo-location with Python.

13条回答
  •  余生分开走
    2020-11-28 04:18

    Maxmind has an official api package that integrates with their geoip web service or geolite databases. You'll have to either download their free geolite database or create a free trial account.

    If you register for an account you'll get $5 in promotional credit (paid queries cost about $0.0001 each). Login to your account, click on 'My License Key' and create a license key.

    Then install the package:

    $ pip install geoip2

    And test the api:

    Test function adapted from the docs

    import geoip2.webservice
    
    account_id = 1 # enter your real account id here
    api_key = "enter your real api/license key here"
    
    TEST_IP = '128.101.101.101'
    
    
    def lookup_ip(ip=TEST_IP):
        # This creates a Client object that can be reused across requests.
        client = geoip2.webservice.Client(account_id, api_key)
    
        # Replace "insights" with the method corresponding to the web service
        # that you are using, e.g., "country", "city".
        response = client.insights(ip)
    
        print("country iso code: {0}".format(response.country.iso_code))
    
        print("country name: {0}".format(response.country.name))
    
        print("subdivisions most specific name: {0}".format(response.subdivisions.most_specific.name))
        print("subdivisions most specific iso code: {0}".format(response.subdivisions.most_specific.iso_code))
    
        print("city name: {0}".format(response.city.name))
    
        print("postal code:{0}".format(response.postal.code))
    
        print("coordinates: ({0}, {1})".format(response.location.latitude, response.location.longitude))
    
        return response
    
    
    if __name__ == "__main__":
        resp = lookup_ip()
        input("")
    

提交回复
热议问题