From dd4374857a283492e9b6c8cd114af091e9074858 Mon Sep 17 00:00:00 2001 From: Robbie Date: Thu, 12 Oct 2023 15:22:42 +0100 Subject: [PATCH] feat: Add django command for geoip (#17947) * Add django command for geoip * Support multiple ips in one command * Add pretty printing and the cache enum --- posthog/management/commands/run_geoip.py | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 posthog/management/commands/run_geoip.py diff --git a/posthog/management/commands/run_geoip.py b/posthog/management/commands/run_geoip.py new file mode 100644 index 0000000000000..31ba761a93268 --- /dev/null +++ b/posthog/management/commands/run_geoip.py @@ -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