📜  pip install geoip2 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 14:45:30.761000             🧑  作者: Mango

Pip Install GeoIP2 - Shell/Bash

The GeoIP2 module allows you to look up geographic information for IP addresses. This module uses the MaxMind GeoIP2 Precision Web Services to provide the geo- location information.

How to Install

To install the GeoIP2 module, simply run the following command:

pip install geoip2
How to Use

To use the GeoIP2 module in Python, you first need to import the module:

import geoip2.webservice

You will also need a MaxMind account ID and license key, which you can obtain from https://www.maxmind.com. With this information, you can then create a geoip2.webservice.Client object:

# Replace with your MaxMind account ID and license key
client = geoip2.webservice.Client('ACCOUNT_ID', 'LICENSE_KEY')

Use this client object to perform IP address lookups:

response = client.city('128.101.101.101')

response will be a geoip2.models.City object containing the geographic information for the IP address.

Here's a more complete example that looks up the geographic information for the visitor's IP address:

from flask import Flask, request
import geoip2.webservice

app = Flask(__name__)

# Replace with your MaxMind account ID and license key
client = geoip2.webservice.Client('ACCOUNT_ID', 'LICENSE_KEY')

@app.route('/')
def index():
    ip = request.environ.get('HTTP_X_FORWARDED_FOR', request.remote_addr)
    response = client.city(ip)
    return f"Ip address {ip} is located in {response.city.name}, {response.subdivisions.most_specific.name}, {response.country.name}"

if __name__ == '__main__':
    app.run()
Conclusion

With the GeoIP2 module, you can easily look up geographic information for IP addresses in your Python applications. By using MaxMind's Precision Web Services, you can be sure that you are getting accurate and up-to-date information.