Skip to content

Commit

Permalink
Cleaning up (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
why-not-try-calmer authored Jun 12, 2023
1 parent e17c242 commit b09e047
Show file tree
Hide file tree
Showing 12 changed files with 46 additions and 83 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ src/django_oapif/__version__.py
static
media
_test_outputs
.vscode/
21 changes: 0 additions & 21 deletions .vscode/launch.json

This file was deleted.

3 changes: 0 additions & 3 deletions .vscode/settings.json

This file was deleted.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ requires = ["setuptools>=45", "setuptools_scm[toml]==7.*"]
build-backend = "setuptools.build_meta"

[project]
requires-python = ">=3.9"
name = "django-ogcapif"
authors = [
{name = "OPENGIS.ch", email = "info@opengis.ch"},
Expand Down Expand Up @@ -30,4 +31,4 @@ root = ".."
[tool.setuptools.dynamic]
readme = {file = ["README.md"], content-type = "text/markdown"}
dependencies = {file = ["requirements.txt"]}
optional-dependencies.dev = {file = ["requirements-dev.txt"]}
optional-dependencies = {file = ["requirements-dev.txt"]}
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
django>=4
django-computedfields
psycopg2
psycopg2-binary
transifex-client
djangorestframework
djangorestframework-gis
Expand Down
66 changes: 17 additions & 49 deletions src/django_oapif/decorators.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
from os import getenv
from typing import Any, Callable, Dict, Optional

from django.contrib.gis.geos import Polygon
from django.db.models import Model
from django.http import HttpResponseBadRequest
from pyproj import CRS, Transformer
from rest_framework import viewsets
from rest_framework_gis.serializers import GeoFeatureModelSerializer

from django_oapif.mixins import OAPIFDescribeModelViewSetMixin
from django_oapif.urls import oapif_router

from .crs_utils import get_crs_from_uri
from .filters import BboxFilterBackend


Expand Down Expand Up @@ -49,16 +44,17 @@ class Meta:
fields = "__all__"
geo_field = "geom"

""" ON HOLD, WAITING ON GeoFeatureModelSerializer to admit of null geometries """
# class AutoNoGeomSerializer(ModelSerializer):
# class Meta:
# model = Model
# fields = "__all__"

# if skip_geom:
# viewset_serializer_class = AutoNoGeomSerializer
# viewset_oapif_geom_lookup = None
# else:
# ON HOLD, WAITING ON GeoFeatureModelSerializer to admit of null geometries
"""
class AutoNoGeomSerializer(ModelSerializer):
class Meta:
model = Model
fields = "__all__
if skip_geom:
viewset_serializer_class = AutoNoGeomSerializer
viewset_oapif_geom_lookup = None
else:
"""
viewset_serializer_class = AutoSerializer
viewset_oapif_geom_lookup = (
"geom" # one day this will be retrieved automatically from the serializer
Expand All @@ -80,41 +76,13 @@ class Viewset(OAPIFDescribeModelViewSetMixin, viewsets.ModelViewSet):
# Allowing '.' and '-' in urls
lookup_value_regex = r"[\w.-]+"

def get_queryset(self):
# Override get_queryset to catch bbox-crs
queryset = super().get_queryset()

if self.request.GET.get("bbox"):
coords = self.request.GET["bbox"].split(",")
user_crs = self.request.GET.get("bbox-crs")

if user_crs:
try:
user_crs = get_crs_from_uri(user_crs)
except:
return HttpResponseBadRequest(
"This API supports only EPSG-specified CRS. Make sure to use the appropriate value for the `bbox-crs`query parameter."
)
api_crs = CRS.from_epsg(int(getenv("GEOMETRY_SRID", "2056")))
transformer = Transformer.from_crs(user_crs, api_crs)
LL = transformer.transform(coords[0], coords[1])
UR = transformer.transform(coords[2], coords[3])
my_bbox_polygon = Polygon.from_bbox(
[LL[0], LL[1], UR[0], UR[1]]
)

else:
my_bbox_polygon = Polygon.from_bbox(coords)

return queryset.filter(geom__intersects=my_bbox_polygon)

return queryset.all()

# ON HOLD, WAITING ON GeoFeatureModelSerializer to admit of null geometries
"""
# Apply custom serializer attributes
# if viewset_serializer_class.__name__ == "AutoNoGeomSerializer":
# for k, v in custom_serializer_attrs.items():
# setattr(AutoNoGeomSerializer.Meta, k, v)

if viewset_serializer_class.__name__ == "AutoNoGeomSerializer":
for k, v in custom_serializer_attrs.items():
setattr(AutoNoGeomSerializer.Meta, k, v)
"""
# Apply custom serializer attributes
for k, v in custom_serializer_attrs.items():
setattr(AutoSerializer.Meta, k, v)
Expand Down
23 changes: 19 additions & 4 deletions src/django_oapif/filters.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from os import getenv

from django.contrib.gis.geos import Polygon
from pyproj import CRS, Transformer
from rest_framework.filters import BaseFilterBackend

from .crs_utils import get_crs_from_uri


# Adapted from rest_framework_gis.filters.InBBoxFilter
class BboxFilterBackend(BaseFilterBackend):
Expand All @@ -9,10 +14,20 @@ def filter_queryset(self, request, queryset, view):
if not bbox_string:
return queryset

p1x, p1y, p2x, p2y = (float(n) for n in bbox_string.split(","))
# TODO: take into account bbox-crs which may differ from the geom
bbox = Polygon.from_bbox((p1x, p1y, p2x, p2y))
# TODO: geom shouldn't be hardcoded here
coords = tuple(float(n) for n in bbox_string.split(","))
user_crs = request.query_params.get("bbox-crs")

if user_crs:
user_crs = get_crs_from_uri(user_crs)
api_crs = CRS.from_epsg(int(getenv("GEOMETRY_SRID", "2056")))
transformer = Transformer.from_crs(user_crs, api_crs)
LL = transformer.transform(coords[0], coords[1])
UR = transformer.transform(coords[2], coords[3])
bbox = Polygon.from_bbox([LL[0], LL[1], UR[0], UR[1]])

else:
bbox = Polygon.from_bbox(coords)

return queryset.filter(geom__bboverlaps=bbox)

def get_schema_operation_parameters(self, view):
Expand Down
2 changes: 1 addition & 1 deletion src/django_oapif/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def get_paginated_response(self, data):
],
"numberReturned": len(data["features"]),
"numberMatched": self.count,
**data, # this looks to be unpacked by LimitOffsetPagination anyway
**data,
}
)

Expand Down
1 change: 0 additions & 1 deletion src/django_oapif/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class OAPIFRouter(routers.SimpleRouter):
"""

include_format_suffixes = True
# default_schema_renderers = None
APISchemaView = SchemaView
SchemaGenerator = SchemaGenerator

Expand Down
4 changes: 4 additions & 0 deletions src/signalo/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ def geom(self):
],
)
def offset_px(self) -> int:
"""
Recalculates offset whenever a new Sign instance
occurs on the same pole
"""
default_padding_px = 5
previous_signs_on_pole = Sign.objects.filter(
azimuth__pole__id=self.azimuth.pole.id, order__lt=self.order
Expand Down
1 change: 0 additions & 1 deletion src/signalo/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ class PoleHighPerfViewset(OAPIFDescribeModelViewSetMixin, viewsets.ModelViewSet)
pagination_class = HighPerfPagination
oapif_title = "Poles (high perf)"
oapif_description = "Poles layer - including high performance optimization"
# (one day this will be retrieved automatically from the serializer)
oapif_geom_lookup = "geom"

def list(self, request, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion src/signalo/roads/management/commands/populate_roads.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def handle(self, *args, **kwargs):
if batch:
Road.objects.bulk_create(batch)
len_batch = len(batch)
total += len(batch)
total += len_batch
print(f"{len_batch} more roads...")
else:
break
Expand Down

0 comments on commit b09e047

Please sign in to comment.