1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Fixed #33866 -- Added pathlib.Path support to GDALRaster constructor.

This commit is contained in:
Claude Paroz 2022-07-25 18:33:25 +02:00 committed by Mariusz Felisiak
parent 36cd425943
commit 2d23a07817
4 changed files with 20 additions and 4 deletions

View File

@ -12,6 +12,7 @@ from ctypes import (
c_void_p,
string_at,
)
from pathlib import Path
from django.contrib.gis.gdal.driver import Driver
from django.contrib.gis.gdal.error import GDALException
@ -83,7 +84,8 @@ class GDALRaster(GDALRasterBase):
ds_input = json.loads(ds_input)
# If input is a valid file path, try setting file as source.
if isinstance(ds_input, str):
if isinstance(ds_input, (str, Path)):
ds_input = str(ds_input)
if not ds_input.startswith(VSI_FILESYSTEM_PREFIX) and not os.path.exists(
ds_input
):

View File

@ -1107,9 +1107,10 @@ blue.
raster should be opened in write mode. For newly-created rasters, the second
parameter is ignored and the new raster is always created in write mode.
The first parameter can take three forms: a string representing a file path
(filesystem or GDAL virtual filesystem), a dictionary with values defining
a new raster, or a bytes object representing a raster file.
The first parameter can take three forms: a string or
:class:`~pathlib.Path` representing a file path (filesystem or GDAL virtual
filesystem), a dictionary with values defining a new raster, or a bytes
object representing a raster file.
If the input is a file path, the raster is opened from there. If the input
is raw data in a dictionary, the parameters ``width``, ``height``, and
@ -1160,6 +1161,10 @@ blue.
>>> rst.name # Stored in a random path in the vsimem filesystem.
'/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
.. versionchanged:: 4.2
Support for :class:`pathlib.Path` ``ds_input`` was added.
.. attribute:: name
The name of the source which is equivalent to the input file path or the name

View File

@ -57,6 +57,9 @@ Minor features
``id`` key for serialized features, which defaults to the primary key of
objects.
* The :class:`~django.contrib.gis.gdal.GDALRaster` class now supports
:class:`pathlib.Path`.
:mod:`django.contrib.messages`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -3,6 +3,7 @@ import shutil
import struct
import tempfile
import zipfile
from pathlib import Path
from unittest import mock
from django.contrib.gis.gdal import GDALRaster, SpatialReference
@ -25,6 +26,11 @@ class GDALRasterTests(SimpleTestCase):
)
self.rs = GDALRaster(self.rs_path)
def test_gdalraster_input_as_path(self):
rs_path = Path(__file__).parent.parent / "data" / "rasters" / "raster.tif"
rs = GDALRaster(rs_path)
self.assertEqual(str(rs_path), rs.name)
def test_rs_name_repr(self):
self.assertEqual(self.rs_path, self.rs.name)
self.assertRegex(repr(self.rs), r"<Raster object at 0x\w+>")