Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run pyupgrade to modernize code - DATA-4232 #1

Merged
merged 1 commit into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions spillway/carto.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def build_map(querysets, tileform):
return m


class Map(object):
class Map:
mapfile = default_storage.path("map.xml")

def __init__(self, width=256, height=256):
Expand Down Expand Up @@ -97,7 +97,7 @@ def zoom_bbox(self, bbox):
self.map.zoom_to_box(mapnik.Box2d(*bbox.extent))


class Layer(object):
class Layer:
"""Base class for a Mapnik layer."""

def __getattr__(self, attr):
Expand Down
8 changes: 4 additions & 4 deletions spillway/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ def as_feature(data):
data = Feature(**data)
elif has_features(data):
data = FeatureCollection(**data)
elif isinstance(data, collections.Sequence):
elif isinstance(data, collections.abc.Sequence):
data = FeatureCollection(features=data)
elif has_layer(data):
data = LayerCollection(data)
elif has_coordinates(data):
data = Feature(geometry=data)
elif isinstance(data, collections.Mapping) and not data:
elif isinstance(data, collections.abc.Mapping) and not data:
data = Feature()
return data

Expand Down Expand Up @@ -136,7 +136,7 @@ def geojson(self):
geom = self["geometry"] or "{}"
keys = self.keys() - {"geometry"}
props = json.dumps({k: self[k] for k in keys}, cls=JSONEncoder)[1:-1]
return '{"geometry": %s, %s}' % (str(geom), props)
return '{{"geometry": {}, {}}}'.format(str(geom), props)


class FeatureCollection(AbstractFeature):
Expand Down Expand Up @@ -182,5 +182,5 @@ def __init__(self, iterable=(), **kwargs):

@property
def geojson(self):
layers = ",".join(['"%s": %s' % (k, v.geojson) for k, v in self.items()])
layers = ",".join(['"{}": {}'.format(k, v.geojson) for k, v in self.items()])
return "{%s}" % layers
2 changes: 1 addition & 1 deletion spillway/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class JSONEncoder(json.JSONEncoder):
import mapnik
except ImportError:

class Mapnik(object):
class Mapnik:
def __getattr__(self, attr):
raise ImproperlyConfigured("Mapnik must be installed")

Expand Down
2 changes: 1 addition & 1 deletion spillway/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get_attribute(self, instance):

def to_internal_value(self, data):
# forms.GeometryField cannot handle geojson dicts.
if isinstance(data, collections.Mapping):
if isinstance(data, collections.abc.Mapping):
data = json.dumps(data)
field = fields.GeometryField(widget=forms.BaseGeometryWidget())
return field.to_python(data)
Expand Down
2 changes: 1 addition & 1 deletion spillway/forms/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def to_python(self, value):
sref = None
# Work with a single GeoJSON geometry or a Feature.
value = json.loads(value) if '"Feature"' in value else value
if isinstance(value, collections.Mapping):
if isinstance(value, collections.abc.Mapping):
feat = sc.as_feature(value)
value = json.dumps(feat.get("geometry") or value)
sref = feat.srs
Expand Down
10 changes: 5 additions & 5 deletions spillway/forms/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class QuerySetForm(forms.Form):
"""Base form for applying GeoQuerySet methods and filters."""

def __init__(self, data=None, queryset=None, *args, **kwargs):
super(QuerySetForm, self).__init__(data, *args, **kwargs)
super().__init__(data, *args, **kwargs)
self.queryset = queryset
self._is_selected = False

Expand Down Expand Up @@ -57,7 +57,7 @@ class SpatialQueryForm(QuerySetForm):
bbox = fields.BoundingBoxField(required=False)

def __init__(self, *args, **kwargs):
super(SpatialQueryForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
lookups = GeometryField.get_lookups()
for lookup in self.data:
if lookup in lookups:
Expand All @@ -67,7 +67,7 @@ def __init__(self, *args, **kwargs):
break

def clean(self):
cleaned_data = super(SpatialQueryForm, self).clean()
cleaned_data = super().clean()
spatial_lookup = set(cleaned_data.keys()) - {"bbox"}
bbox = cleaned_data.pop("bbox", None)
# Look for "bbox" which is just an alias to "bboverlaps".
Expand Down Expand Up @@ -131,7 +131,7 @@ def clean(self):
"""Return cleaned fields as a dict, determine which geom takes
precedence.
"""
data = super(RasterQueryForm, self).clean()
data = super().clean()
geom = data.pop("upload", None) or data.pop("bbox", None)
if geom:
data["g"] = geom
Expand Down Expand Up @@ -170,7 +170,7 @@ class TileForm(QuerySetForm):
z = forms.IntegerField()

def clean(self):
data = super(TileForm, self).clean()
data = super().clean()
x, y, z = map(data.get, ("x", "y", "z"))
# Create bbox from NW and SE tile corners.
try:
Expand Down
4 changes: 2 additions & 2 deletions spillway/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from rest_framework.settings import api_settings


class ModelSerializerMixin(object):
class ModelSerializerMixin:
"""Provides generic model serializer classes to views."""

model_serializer_class = None
Expand All @@ -20,7 +20,7 @@ class Meta:
return DefaultSerializer


class ResponseExceptionMixin(object):
class ResponseExceptionMixin:
"""Handle response exceptions by negotating among default renderers.

The default exception handler passes error message dicts to the renderer
Expand Down
2 changes: 1 addition & 1 deletion spillway/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# Workaround for migrations and FileField upload_to, see:
# https://code.djangoproject.com/ticket/22999
@deconstructible
class UploadDir(object):
class UploadDir:
def __init__(self, path):
self.path = path

Expand Down
2 changes: 1 addition & 1 deletion spillway/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def filter_geometry(queryset, **filters):
usual "geometryfield__lookuptype" format.
"""
fieldname = geo_field(queryset).name
query = {"%s__%s" % (fieldname, k): v for k, v in filters.items()}
query = {"{}__{}".format(fieldname, k): v for k, v in filters.items()}
return queryset.filter(**query)


Expand Down
2 changes: 1 addition & 1 deletion spillway/renderers/gdal.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class GeoTIFFZipRenderer(BaseGDALRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
if len(data) > 1:
raise ValueError("Expected one-length sequence")
return super(GeoTIFFZipRenderer, self).render(
return super().render(
data[0], accepted_media_type, renderer_context
)

Expand Down
4 changes: 2 additions & 2 deletions spillway/renderers/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def render(self, data, accepted_media_type=None, renderer_context=None):
try:
return data.geojson
except AttributeError:
return super(GeoJSONRenderer, self).render(
return super().render(
data, accepted_media_type, renderer_context
)

Expand Down Expand Up @@ -57,7 +57,7 @@ class KMZRenderer(KMLRenderer):
format = "kmz"

def render(self, *args, **kwargs):
kmldata = super(KMZRenderer, self).render(*args, **kwargs)
kmldata = super().render(*args, **kwargs)
return compress_kml(kmldata)


Expand Down
2 changes: 1 addition & 1 deletion spillway/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
# Regex for an optional file extension.
format_suffix = r"(?:\.(?P<format>[\w.]+))?"
# Regex groups for a tile URL in {z}/{x}/{y}.{format} order.
tile = ("(?P<z>\d+)", "(?P<x>\d+)", "(?P<y>\d+)%s/?$" % format_suffix)
tile = (r"(?P<z>\d+)", r"(?P<x>\d+)", r"(?P<y>\d+)%s/?$" % format_suffix)
tileregex = sep.join(tile)


Expand Down
2 changes: 1 addition & 1 deletion spillway/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


@deconstructible
class GeometrySizeValidator(object):
class GeometrySizeValidator:
"""Field validator to limit geometries to a given area."""

message = _("Max area exceeded.")
Expand Down
2 changes: 1 addition & 1 deletion tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Meta:
ordering = ["id"]

def __repr__(self):
return "<%s: %s %s>" % (self.__class__.__name__, self.name, self.geom)
return "<{}: {} {}>".format(self.__class__.__name__, self.name, self.geom)

def __str__(self):
return self.name
Expand Down
6 changes: 3 additions & 3 deletions tests/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,16 +219,16 @@ def test_paginate_geojson(self):
class RasterListViewTestCase(RasterStoreTestBase):
def test_list_apidoc(self):
response = self.client.get("/rasters/", {"format": "api"})
self.assertRegexpMatches(
response.content.decode("utf-8"), "image.+?http://.*\.tif"
self.assertRegex(
response.content.decode("utf-8"), r"image.+?http://.*\.tif"
)
point = self.object.geom.centroid
response = self.client.get("/rasters/", {"format": "api", "g": point.wkt})
self.assertEqual(response.data[0]["image"], 12)

def test_list_json(self):
d = self.client.get("/rasters/").json()
self.assertRegexpMatches(d[0]["image"], "^http://.*\.tif$")
self.assertRegex(d[0]["image"], r"^http://.*\.tif$")

def test_list_json_array(self):
with Raster(self.object.image.path) as r:
Expand Down
4 changes: 2 additions & 2 deletions tests/test_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,15 +98,15 @@ def assert_member_formats(self, rend, geom=None):
ext = rend.format
if rend.format.endswith(".zip"):
ext = os.path.splitext(rend.format)[0]
pat = "tmin_.+(?<!\.{0})\.{0}$".format(ext)
pat = r"tmin_.+(?<!\.{0})\.{0}$".format(ext)
driver = driver_for_path(ext, ImageDriver.filter_copyable())
qs = self.qs.warp(format=driver.ext, geom=geom)
lst = [obj.raster() for obj in qs]
rs = RasterStoreSerializer(qs.zipfiles(), many=True)
fp = rend.render(rs.data)
with zipfile.ZipFile(fp) as zf:
for r, name in zip(lst, zf.namelist()):
self.assertRegexpMatches(name, pat)
self.assertRegex(name, pat)
imgdata = zf.read(name)
self.assert_format(imgdata, driver.format)
memio = MemFileIO()
Expand Down
6 changes: 3 additions & 3 deletions tests/test_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .test_models import RasterStoreTestBase


class RequestMock(object):
class RequestMock:
def __init__(self):
self.accepted_renderer = renderers.JSONRenderer()
self.GET = {}
Expand Down Expand Up @@ -112,7 +112,7 @@ def test_serialize_object(self):

class FeatureSerializerTestCase(ModelTestCase):
def setUp(self):
super(FeatureSerializerTestCase, self).setUp()
super().setUp()
attrs = {
"id": 1,
"crs": 4326,
Expand Down Expand Up @@ -197,7 +197,7 @@ def test_deserialize_list(self):

class RasterSerializerTestCase(RasterStoreTestBase):
def setUp(self):
super(RasterSerializerTestCase, self).setUp()
super().setUp()
self.request = RequestMock()
self.ctx = {"request": self.request}

Expand Down
2 changes: 1 addition & 1 deletion tests/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
name="location-tiles",
),
url(
tilepath("^maptiles/(?P<pk>\d+)/"),
tilepath(r"^maptiles/(?P<pk>\d+)/"),
views.RasterTileView.as_view(queryset=RasterStore.objects.all()),
name="map-tiles",
),
Expand Down