refactor: Move get_location to model to avoid circulari mports

This commit is contained in:
moanos [he/him] 2024-05-31 12:17:53 +02:00
parent 6799dbe901
commit d2219188d3
2 changed files with 23 additions and 16 deletions

View File

@ -10,7 +10,7 @@ from django.db.models.signals import post_save
from django.contrib.auth.models import Group
from django.contrib.auth.models import AbstractUser
from fellchensammlung.tools import misc
from fellchensammlung.tools import misc, geo
from notfellchen.settings import MEDIA_URL
@ -71,6 +71,26 @@ class Location(models.Model):
longitude = models.FloatField()
name = models.CharField(max_length=2000)
def __str__(self):
return f"{self.name} ({self.latitude:.5}, {self.longitude:.5})"
@staticmethod
def get_location_from_string(location_string):
geo_api = geo.GeoAPI()
get_geojson = geo_api.get_geojson_for_query(location_string)
result = get_geojson[0]
if "name" in result:
name = result["name"]
else:
name = result["display_name"]
location = Location.objects.create(
place_id=result["place_id"],
latitude=result["lat"],
longitude=result["lon"],
name=name,
)
return location
class RescueOrganization(models.Model):
def __str__(self):

View File

@ -3,7 +3,6 @@ import logging
import requests
import json
from notfellchen import __version__ as nf_version
from fellchensammlung.models import Location
from notfellchen import settings
from math import radians, sqrt, sin, cos, atan2
@ -69,7 +68,7 @@ class GeoAPI:
result = self.requests.get(self.api_url, {"q": location_string, "format": "jsonv2"}, headers=self.headers)
return result.content
def get_location_from_string(self, location_string):
def get_geojson_for_query(self, location_string):
try:
result = self.requests.get(self.api_url,
{"q": location_string,
@ -81,19 +80,7 @@ class GeoAPI:
if len(result) == 0:
logging.warning(f"Couldn't find a result for {location_string} when querying Nominatim")
return None
result = result[0]
if "name" in result:
name = result["name"]
else:
name = result["display_name"]
location = Location.objects.create(
place_id=result["place_id"],
latitude=result["lat"],
longitude=result["lon"],
name=name,
)
return location
return result
if __name__ == "__main__":