Skip to content

Commit

Permalink
Handle IP address location not found (AddressNotFoundError)
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeshingles committed Dec 6, 2024
1 parent 52a5a42 commit 374a516
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions atlasserver/forcephot/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from django.shortcuts import render
from django.views.decorators.cache import cache_page
from django_filters.rest_framework import DjangoFilterBackend
from geoip2.errors import AddressNotFoundError
from rest_framework import filters
from rest_framework import permissions
from rest_framework import status
Expand Down Expand Up @@ -221,10 +222,13 @@ def perform_create(self, serializer) -> None:
ip = x_forwarded_for.split(",")[0]
else:
ip = self.request.META.get("REMOTE_ADDR")

geoip = GeoIP2()
location = geoip.city(ip)
extra_fields["country_code"] = location["country_code"]
extra_fields["region"] = location["region_code"]
with contextlib.suppress(AddressNotFoundError):
location = geoip.city(ip)
extra_fields["country_code"] = location["country_code"]
extra_fields["region"] = location["region_code"]

extra_fields["from_api"] = "HTTP_REFERER" not in self.request.META

serializer.save(**extra_fields)
Expand Down Expand Up @@ -376,9 +380,10 @@ def get(self, request, pk):
else:
ip = self.request.META.get("REMOTE_ADDR")
geoip = GeoIP2()
location = geoip.city(ip)
data["country_code"] = location["country_code"]
data["region"] = location["region_code"]
with contextlib.suppress(AddressNotFoundError):
location = geoip.city(ip)
data["country_code"] = location["country_code"]
data["region"] = location["region_code"]

data["from_api"] = False
data["send_email"] = False
Expand Down

0 comments on commit 374a516

Please sign in to comment.