(self, ds_input, write=False)
| 75 | destructor = capi.close_ds |
| 76 | |
| 77 | def __init__(self, ds_input, write=False): |
| 78 | self._write = 1 if write else 0 |
| 79 | Driver.ensure_registered() |
| 80 | |
| 81 | # Preprocess json inputs. This converts json strings to dictionaries, |
| 82 | # which are parsed below the same way as direct dictionary inputs. |
| 83 | if isinstance(ds_input, str) and json_regex.match(ds_input): |
| 84 | ds_input = json.loads(ds_input) |
| 85 | |
| 86 | # If input is a valid file path, try setting file as source. |
| 87 | if isinstance(ds_input, (str, Path)): |
| 88 | ds_input = str(ds_input) |
| 89 | if not ds_input.startswith(VSI_FILESYSTEM_PREFIX) and not os.path.exists( |
| 90 | ds_input |
| 91 | ): |
| 92 | raise GDALException( |
| 93 | 'Unable to read raster source input "%s".' % ds_input |
| 94 | ) |
| 95 | try: |
| 96 | # GDALOpen will auto-detect the data source type. |
| 97 | self._ptr = capi.open_ds(force_bytes(ds_input), self._write) |
| 98 | except GDALException as err: |
| 99 | raise GDALException( |
| 100 | 'Could not open the datasource at "{}" ({}).'.format(ds_input, err) |
| 101 | ) |
| 102 | elif isinstance(ds_input, bytes): |
| 103 | # Create a new raster in write mode. |
| 104 | self._write = 1 |
| 105 | # Get size of buffer. |
| 106 | size = sys.getsizeof(ds_input) |
| 107 | # Pass data to ctypes, keeping a reference to the ctypes object so |
| 108 | # that the vsimem file remains available until the GDALRaster is |
| 109 | # deleted. |
| 110 | self._ds_input = c_buffer(ds_input) |
| 111 | # Create random name to reference in vsimem filesystem. |
| 112 | vsi_path = os.path.join(VSI_MEM_FILESYSTEM_BASE_PATH, str(uuid.uuid4())) |
| 113 | # Create vsimem file from buffer. |
| 114 | capi.create_vsi_file_from_mem_buffer( |
| 115 | force_bytes(vsi_path), |
| 116 | byref(self._ds_input), |
| 117 | size, |
| 118 | VSI_TAKE_BUFFER_OWNERSHIP, |
| 119 | ) |
| 120 | # Open the new vsimem file as a GDALRaster. |
| 121 | try: |
| 122 | self._ptr = capi.open_ds(force_bytes(vsi_path), self._write) |
| 123 | except GDALException: |
| 124 | # Remove the broken file from the VSI filesystem. |
| 125 | capi.unlink_vsi_file(force_bytes(vsi_path)) |
| 126 | raise GDALException("Failed creating VSI raster from the input buffer.") |
| 127 | elif isinstance(ds_input, dict): |
| 128 | # A new raster needs to be created in write mode |
| 129 | self._write = 1 |
| 130 | |
| 131 | # Create driver (in memory by default) |
| 132 | driver = Driver(ds_input.get("driver", "MEM")) |
| 133 | |
| 134 | # For out of memory drivers, check filename argument |
no test coverage detected