1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-08-02 19:55:18 +02:00

chore: Add GeoJSON endpoint to retrieve combined GeoJSON data from static files

This commit is contained in:
Sean Morley 2024-07-27 12:46:50 -04:00
parent 70d08eff8a
commit 57eee7bb5d
4 changed files with 83 additions and 25 deletions

View file

@ -2,7 +2,7 @@
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import CountryViewSet, RegionViewSet, VisitedRegionViewSet, regions_by_country, visits_by_country
from .views import CountryViewSet, RegionViewSet, VisitedRegionViewSet, regions_by_country, visits_by_country, GeoJSONView
router = DefaultRouter()
router.register(r'countries', CountryViewSet, basename='countries')
@ -13,4 +13,5 @@ urlpatterns = [
path('', include(router.urls)),
path('<str:country_code>/regions/', regions_by_country, name='regions-by-country'),
path('<str:country_code>/visits/', visits_by_country, name='visits-by-country'),
path('geojson/', GeoJSONView.as_view({'get': 'list'}), name='geojson'),
]

View file

@ -6,6 +6,10 @@ from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
import os
import json
from django.conf import settings
from django.contrib.staticfiles import finders
@api_view(['GET'])
@permission_classes([IsAuthenticated])
@ -49,4 +53,38 @@ class VisitedRegionViewSet(viewsets.ModelViewSet):
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
class GeoJSONView(viewsets.ViewSet):
"""
Combine all GeoJSON data from .json files in static/data into a single GeoJSON object.
"""
def list(self, request):
combined_geojson = {
"type": "FeatureCollection",
"features": []
}
# Use Django's static file finder to locate the 'data' directory
data_dir = finders.find('data')
if not data_dir or not os.path.isdir(data_dir):
return Response({"error": "Data directory does not exist."}, status=404)
for filename in os.listdir(data_dir):
if filename.endswith('.json'):
file_path = os.path.join(data_dir, filename)
try:
with open(file_path, 'r') as f:
json_data = json.load(f)
# Check if the JSON data is GeoJSON
if isinstance(json_data, dict) and "type" in json_data:
if json_data["type"] == "FeatureCollection":
combined_geojson["features"].extend(json_data.get("features", []))
elif json_data["type"] == "Feature":
combined_geojson["features"].append(json_data)
# You can add more conditions here for other GeoJSON types if needed
except (IOError, json.JSONDecodeError) as e:
return Response({"error": f"Error reading file {filename}: {str(e)}"}, status=500)
return Response(combined_geojson)