Skip to content

Commit d985ff9

Browse files
Refactor with black (#226)
1 parent 666b818 commit d985ff9

File tree

17 files changed

+159
-89
lines changed

17 files changed

+159
-89
lines changed

importer/handlers/base.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,7 @@ def fixup_name(self, name):
119119
.replace(")", "")
120120
.replace("(", "")
121121
.replace(",", "")
122-
.replace("&", "")
123-
[:62]
122+
.replace("&", "")[:62]
124123
)
125124

126125
def extract_resource_to_publish(self, files, layer_name, alternate, **kwargs):
@@ -132,7 +131,7 @@ def extract_resource_to_publish(self, files, layer_name, alternate, **kwargs):
132131
]
133132
"""
134133
return NotImplementedError
135-
134+
136135
def overwrite_geoserver_resource(self, resource, catalog, store, workspace):
137136
"""
138137
Base method for override the geoserver resource. For vector file usually

importer/handlers/common/raster.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -130,15 +130,21 @@ def publish_resources(resources: List[str], catalog, store, workspace):
130130
raise e
131131
return True
132132

133-
def overwrite_geoserver_resource(self, resource: List[str], catalog, store, workspace):
133+
def overwrite_geoserver_resource(
134+
self, resource: List[str], catalog, store, workspace
135+
):
134136
# we need to delete the resource before recreating it
135137
self._delete_resource(resource, catalog, workspace)
136138
self._delete_store(resource, catalog, workspace)
137139
return self.publish_resources([resource], catalog, store, workspace)
138140

139141
def _delete_store(self, resource, catalog, workspace):
140142
store = None
141-
possible_layer_name = [resource.get("name"), resource.get("name").split(":")[-1], f"{workspace.name}:{resource.get('name')}"]
143+
possible_layer_name = [
144+
resource.get("name"),
145+
resource.get("name").split(":")[-1],
146+
f"{workspace.name}:{resource.get('name')}",
147+
]
142148
for el in possible_layer_name:
143149
store = catalog.get_store(el, workspace=workspace)
144150
if store:
@@ -149,7 +155,11 @@ def _delete_store(self, resource, catalog, workspace):
149155

150156
def _delete_resource(self, resource, catalog, workspace):
151157
res = None
152-
possible_layer_name = [resource.get("name"), resource.get("name").split(":")[-1], f"{workspace.name}:{resource.get('name')}"]
158+
possible_layer_name = [
159+
resource.get("name"),
160+
resource.get("name").split(":")[-1],
161+
f"{workspace.name}:{resource.get('name')}",
162+
]
153163
for el in possible_layer_name:
154164
res = catalog.get_resource(el, workspace=workspace)
155165
if res:
@@ -221,9 +231,9 @@ def extract_resource_to_publish(
221231
return [
222232
{
223233
"name": alternate or layer_name,
224-
"crs": self.identify_authority(layers)
225-
if layers.GetSpatialRef()
226-
else None,
234+
"crs": (
235+
self.identify_authority(layers) if layers.GetSpatialRef() else None
236+
),
227237
"raster_path": files.get("base_file"),
228238
}
229239
]
@@ -388,7 +398,7 @@ def overwrite_geonode_resource(
388398
_overwrite = _exec.input_params.get("overwrite_existing_layer", False)
389399
# if the layer exists, we just update the information of the dataset by
390400
# let it recreate the catalogue
391-
401+
392402
if dataset.exists() and _overwrite:
393403
dataset = dataset.first()
394404

@@ -511,7 +521,7 @@ def rollback(
511521
):
512522
steps = self.ACTIONS.get(action_to_rollback)
513523
if rollback_from_step not in steps:
514-
return
524+
return
515525
step_index = steps.index(rollback_from_step)
516526
# the start_import, start_copy etc.. dont do anything as step, is just the start
517527
# so there is nothing to rollback

importer/handlers/common/tests_vector.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,11 @@ def test_import_with_ogr2ogr_without_errors_should_call_the_right_command(
226226

227227
_open.assert_called_once()
228228
_open.assert_called_with(
229-
f'/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:" dbname=\'test_geonode_data\' host=' + os.getenv('DATABASE_HOST', 'localhost') + ' port=5432 user=\'geonode_data\' password=\'geonode_data\' " "' + self.valid_files.get("base_file") + '" -nln alternate "dataset"',
229+
f"/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:\" dbname='test_geonode_data' host="
230+
+ os.getenv("DATABASE_HOST", "localhost")
231+
+ " port=5432 user='geonode_data' password='geonode_data' \" \""
232+
+ self.valid_files.get("base_file")
233+
+ '" -nln alternate "dataset"',
230234
stdout=-1,
231235
stderr=-1,
232236
shell=True, # noqa
@@ -252,7 +256,11 @@ def test_import_with_ogr2ogr_with_errors_should_raise_exception(self, _open):
252256

253257
_open.assert_called_once()
254258
_open.assert_called_with(
255-
f'/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:" dbname=\'test_geonode_data\' host=' + os.getenv('DATABASE_HOST', 'localhost') + ' port=5432 user=\'geonode_data\' password=\'geonode_data\' " "' + self.valid_files.get("base_file") + '" -nln alternate "dataset"',
259+
f"/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:\" dbname='test_geonode_data' host="
260+
+ os.getenv("DATABASE_HOST", "localhost")
261+
+ " port=5432 user='geonode_data' password='geonode_data' \" \""
262+
+ self.valid_files.get("base_file")
263+
+ '" -nln alternate "dataset"',
256264
stdout=-1,
257265
stderr=-1,
258266
shell=True, # noqa
@@ -284,7 +292,7 @@ def test_import_with_ogr2ogr_without_errors_should_call_the_right_command_if_dum
284292

285293
_open.assert_called_once()
286294
_call_as_string = _open.mock_calls[0][1][0]
287-
288-
self.assertTrue('-f PGDump /vsistdout/' in _call_as_string)
289-
self.assertTrue('psql -d' in _call_as_string)
290-
self.assertFalse('-f PostgreSQL PG' in _call_as_string)
295+
296+
self.assertTrue("-f PGDump /vsistdout/" in _call_as_string)
297+
self.assertTrue("psql -d" in _call_as_string)
298+
self.assertFalse("-f PostgreSQL PG" in _call_as_string)

importer/handlers/common/vector.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,7 @@ def publish_resources(resources: List[str], catalog, store, workspace):
130130
jdbc_virtual_table=_resource.get("name"),
131131
)
132132
except Exception as e:
133-
if (
134-
f"Resource named {_resource} already exists in store:"
135-
in str(e)
136-
):
133+
if f"Resource named {_resource} already exists in store:" in str(e):
137134
logger.error(f"error during publishing: {e}")
138135
continue
139136
logger.error(f"error during publishing: {e}")
@@ -154,13 +151,13 @@ def create_ogr2ogr_command(files, original_name, ovverwrite_layer, alternate):
154151
This is a default command that is needed to import a vector file
155152
"""
156153
_datastore = settings.DATABASES["datastore"]
157-
154+
158155
options = "--config PG_USE_COPY YES"
159156
copy_with_dump = ast.literal_eval(os.getenv("OGR2OGR_COPY_WITH_DUMP", "False"))
160157

161158
if copy_with_dump:
162159
# use PGDump to load the dataset with ogr2ogr
163-
options += ' -f PGDump /vsistdout/ '
160+
options += " -f PGDump /vsistdout/ "
164161
else:
165162
# default option with postgres copy
166163
options += (
@@ -520,11 +517,13 @@ def create_dynamic_model_fields(
520517
ogr.GeometryTypeToName(layer.GetGeomType())
521518
)
522519
),
523-
"dim": 2
524-
if not ogr.GeometryTypeToName(layer.GetGeomType())
525-
.lower()
526-
.startswith("3d")
527-
else 3,
520+
"dim": (
521+
2
522+
if not ogr.GeometryTypeToName(layer.GetGeomType())
523+
.lower()
524+
.startswith("3d")
525+
else 3
526+
),
528527
}
529528
]
530529

importer/handlers/csv/handler.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -195,11 +195,13 @@ def create_dynamic_model_fields(
195195
"name": layer.GetGeometryColumn()
196196
or self.default_geometry_column_name,
197197
"class_name": class_name,
198-
"dim": 2
199-
if not ogr.GeometryTypeToName(layer.GetGeomType())
200-
.lower()
201-
.startswith("3d")
202-
else 3,
198+
"dim": (
199+
2
200+
if not ogr.GeometryTypeToName(layer.GetGeomType())
201+
.lower()
202+
.startswith("3d")
203+
else 3
204+
),
203205
}
204206
]
205207

@@ -241,9 +243,9 @@ def extract_resource_to_publish(
241243
return [
242244
{
243245
"name": alternate or layer_name,
244-
"crs": self.identify_authority(_l)
245-
if _l.GetSpatialRef()
246-
else "EPSG:4326",
246+
"crs": (
247+
self.identify_authority(_l) if _l.GetSpatialRef() else "EPSG:4326"
248+
),
247249
}
248250
for _l in layers
249251
if self.fixup_name(_l.GetName()) == layer_name

importer/handlers/csv/tests.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,11 @@ def test_import_with_ogr2ogr_without_errors_should_call_the_right_command(
165165

166166
_open.assert_called_once()
167167
_open.assert_called_with(
168-
f'/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:" dbname=\'test_geonode_data\' host=' + os.getenv('DATABASE_HOST', 'localhost') + ' port=5432 user=\'geonode_data\' password=\'geonode_data\' " "' + self.valid_csv + '" -nln alternate "dataset" -oo KEEP_GEOM_COLUMNS=NO -lco GEOMETRY_NAME=geometry -oo "GEOM_POSSIBLE_NAMES=geom*,the_geom*,wkt_geom" -oo "X_POSSIBLE_NAMES=x,long*" -oo "Y_POSSIBLE_NAMES=y,lat*"',
168+
f"/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:\" dbname='test_geonode_data' host="
169+
+ os.getenv("DATABASE_HOST", "localhost")
170+
+ " port=5432 user='geonode_data' password='geonode_data' \" \""
171+
+ self.valid_csv
172+
+ '" -nln alternate "dataset" -oo KEEP_GEOM_COLUMNS=NO -lco GEOMETRY_NAME=geometry -oo "GEOM_POSSIBLE_NAMES=geom*,the_geom*,wkt_geom" -oo "X_POSSIBLE_NAMES=x,long*" -oo "Y_POSSIBLE_NAMES=y,lat*"',
169173
stdout=-1,
170174
stderr=-1,
171175
shell=True, # noqa

importer/handlers/geojson/tests.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,11 @@ def test_import_with_ogr2ogr_without_errors_should_call_the_right_command(
131131

132132
_open.assert_called_once()
133133
_open.assert_called_with(
134-
f'/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:" dbname=\'test_geonode_data\' host=' + os.getenv('DATABASE_HOST', 'localhost') + ' port=5432 user=\'geonode_data\' password=\'geonode_data\' " "' + self.valid_files.get("base_file") + '" -nln alternate "dataset" -lco GEOMETRY_NAME=geometry',
134+
f"/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:\" dbname='test_geonode_data' host="
135+
+ os.getenv("DATABASE_HOST", "localhost")
136+
+ " port=5432 user='geonode_data' password='geonode_data' \" \""
137+
+ self.valid_files.get("base_file")
138+
+ '" -nln alternate "dataset" -lco GEOMETRY_NAME=geometry',
135139
stdout=-1,
136140
stderr=-1,
137141
shell=True, # noqa

importer/handlers/gpkg/tests.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,7 @@ def test_is_valid_should_raise_exception_if_the_gpkg_is_invalid(self):
5656
self.handler.is_valid(files=self.invalid_files, user=self.user)
5757

5858
self.assertIsNotNone(_exc)
59-
self.assertTrue(
60-
"Error layer: INVALID LAYER_name"
61-
in str(_exc.exception.detail)
62-
)
59+
self.assertTrue("Error layer: INVALID LAYER_name" in str(_exc.exception.detail))
6360

6461
def test_is_valid_should_raise_exception_if_the_parallelism_is_met(self):
6562
parallelism, created = UploadParallelismLimit.objects.get_or_create(

importer/handlers/shapefile/handler.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -123,9 +123,11 @@ def is_valid(files, user):
123123
is_valid = all(
124124
map(
125125
lambda x: any(
126-
_ext.endswith(f"{_filename}.{x}")
127-
if isinstance(_ext, str)
128-
else _ext.name.endswith(f"{_filename}.{x}")
126+
(
127+
_ext.endswith(f"{_filename}.{x}")
128+
if isinstance(_ext, str)
129+
else _ext.name.endswith(f"{_filename}.{x}")
130+
)
129131
for _ext in files.values()
130132
),
131133
_shp_ext_needed,
@@ -156,22 +158,24 @@ def create_ogr2ogr_command(files, original_name, ovverwrite_layer, alternate):
156158
encoding = ShapeFileHandler._get_encoding(files)
157159

158160
additional_options = []
159-
if layer is not None and "Point" not in ogr.GeometryTypeToName(layer.GetGeomType()):
161+
if layer is not None and "Point" not in ogr.GeometryTypeToName(
162+
layer.GetGeomType()
163+
):
160164
additional_options.append("-nlt PROMOTE_TO_MULTI")
161165
if encoding:
162166
additional_options.append(f"-lco ENCODING={encoding}")
163-
167+
164168
return (
165169
f"{base_command } -lco precision=no -lco GEOMETRY_NAME={BaseVectorFileHandler().default_geometry_column_name} "
166170
+ " ".join(additional_options)
167171
)
168-
172+
169173
@staticmethod
170174
def _get_encoding(files):
171175
if files.get("cpg_file"):
172176
# prefer cpg file which is handled by gdal
173177
return None
174-
178+
175179
encoding = None
176180
if files.get("cst_file"):
177181
# GeoServer exports cst-file

importer/handlers/shapefile/tests.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,11 @@ def test_should_create_ogr2ogr_command_with_encoding_from_cst(self):
116116
shp_with_cst = self.valid_shp.copy()
117117
cst_file = self.valid_shp["base_file"].replace("shp", "cst")
118118
shp_with_cst["cst_file"] = cst_file
119-
patch_location = 'importer.handlers.shapefile.handler.open'
120-
with patch(patch_location, new=mock_open(read_data='UTF-8')) as _file:
119+
patch_location = "importer.handlers.shapefile.handler.open"
120+
with patch(patch_location, new=mock_open(read_data="UTF-8")) as _file:
121121
actual = self.handler.create_ogr2ogr_command(shp_with_cst, "a", False, "a")
122-
123-
_file.assert_called_once_with(cst_file, 'r')
122+
123+
_file.assert_called_once_with(cst_file, "r")
124124
self.assertIn("ENCODING=UTF-8", actual)
125125

126126
@patch("importer.handlers.common.vector.Popen")
@@ -148,7 +148,11 @@ def test_import_with_ogr2ogr_without_errors_should_call_the_right_command(
148148

149149
_open.assert_called_once()
150150
_open.assert_called_with(
151-
f'/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:" dbname=\'test_geonode_data\' host=' + os.getenv('DATABASE_HOST', 'localhost') + ' port=5432 user=\'geonode_data\' password=\'geonode_data\' " "' + self.valid_shp.get("base_file") + '" -nln alternate "dataset" -lco precision=no -lco GEOMETRY_NAME=geometry ',
151+
f"/usr/bin/ogr2ogr --config PG_USE_COPY YES -f PostgreSQL PG:\" dbname='test_geonode_data' host="
152+
+ os.getenv("DATABASE_HOST", "localhost")
153+
+ " port=5432 user='geonode_data' password='geonode_data' \" \""
154+
+ self.valid_shp.get("base_file")
155+
+ '" -nln alternate "dataset" -lco precision=no -lco GEOMETRY_NAME=geometry ',
152156
stdout=-1,
153157
stderr=-1,
154158
shell=True, # noqa

importer/handlers/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,9 @@ def create_alternate(layer_name, execution_id):
7272
"""
7373
_hash = hashlib.md5(f"{layer_name}_{execution_id}".encode("utf-8")).hexdigest()
7474
alternate = f"{layer_name}_{_hash}"
75-
if len(alternate) > 63: # 63 is the max table lengh in postgres to stay safe, we cut at 12
75+
if (
76+
len(alternate) > 63
77+
): # 63 is the max table lengh in postgres to stay safe, we cut at 12
7678
return f"{layer_name[:50]}{_hash[:12]}"
7779
return alternate
7880

importer/migrations/0005_fixup_dynamic_shema_table_names.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ def fixup_table_name(apps, schema_editor):
1212
The dynamic model should exists to apply the migration.
1313
In case it does not exists we can skip it
1414
"""
15-
if 'dynamic_models_modelschema' in schema_editor.connection.introspection.table_names():
15+
if (
16+
"dynamic_models_modelschema"
17+
in schema_editor.connection.introspection.table_names()
18+
):
1619
schema = apps.get_model("dynamic_models", "ModelSchema")
1720
for val in schema.objects.all():
1821
if val.name != val.db_table_name:

importer/models.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ def delete_dynamic_model(instance, sender, **kwargs):
3030

3131

3232
class ResourceHandlerInfo(models.Model):
33-
3433
"""
3534
Here we save the relation between the geonode resource created and the handler that created that resource
3635
"""

0 commit comments

Comments
 (0)