Skip to content

Commit

Permalink
save event: in case of a geocoding failure, background the task
Browse files Browse the repository at this point in the history
fixes #163 #153
  • Loading branch information
thomersch committed Mar 28, 2024
1 parent 27dba66 commit 7aefc57
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions osmcal/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import bleach
import markdown
import requests
from background_task import background
from babel.dates import get_timezone_name
from django.contrib.auth.models import AbstractUser
from django.contrib.gis.db.models import PointField
Expand Down Expand Up @@ -52,17 +53,38 @@ class Event(models.Model):
def save(self, *args, **kwargs):
if self.location:
self.geocode_location()

# For the case that an event had previously an address which got removed by the edit:
if not self.location:
self.location_address = None

super().save(*args, **kwargs)

def geocode_location(self):
try:
self._geocode_location()
except:
event_id = self.id
self._background_geocode_location(event_id)

def _geocode_location(self):
nr = requests.get(
"https://nominatim.openstreetmap.org/reverse",
params={"format": "jsonv2", "lat": self.location.y, "lon": self.location.x, "accept-language": "en"},
headers={"User-Agent": "osmcal"},
)
nr.raise_for_status()

self.location_address = nr.json().get("address", None)
if self.location_address is None:
add_breadcrumb(category="nominatim", level="error", data=nr.json())

@staticmethod
@background(schedule=1)
def _background_geocode_location(event_id):
evt = Event.objects.get(id=event_id)
evt.save() # geocodes implicitly

@property
def location_text(self):
if not self.location_address:
Expand Down

0 comments on commit 7aefc57

Please sign in to comment.