Skip to content

Commit

Permalink
feat: Add django command for geoip (#17947)
Browse files Browse the repository at this point in the history
* Add django command for geoip

* Support multiple ips in one command

* Add pretty printing and the cache enum
  • Loading branch information
robbie-c authored Oct 12, 2023
1 parent d49d699 commit dd43748
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions posthog/management/commands/run_geoip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import logging
from pprint import pprint

from django.contrib.gis.geoip2 import GeoIP2
from django.core.management.base import BaseCommand

logging.getLogger("kafka").setLevel(logging.ERROR) # Hide kafka-python's logspam


class Command(BaseCommand):
help = "Run geoip2 for an ip address, try `DEBUG=1 ./manage.py run_geoip 138.84.47.0`"

def add_arguments(self, parser):
parser.add_argument("ip", type=str, help="IP Address")

def handle(self, *args, **options):
geoip = GeoIP2(cache=GeoIP2.MODE_MMAP)
ip_arg = options.get("ip")
if not isinstance(ip_arg, str):
raise ValueError("ip not a string")

ips = ip_arg.split(",")

for ip in ips:
ip = ip.strip()
print("----------------------------------------") # noqa: T201
print(ip) # noqa: T201
pprint(geoip.city(ip)) # noqa: T203

0 comments on commit dd43748

Please sign in to comment.