shapelib.core.handlers package#
Local file handlers for shapelib.
Handlers: - GeoFileHandler: Abstract base class - ShapefileHandler: .shp files - ZippedShapefileHandler: .zip archives with shapefiles - GeoJSONHandler: .geojson/.json files - GeoPackageHandler: .gpkg files - KMLHandler: .kml files - FlatGeobufHandler: .fgb files - SpatiaLiteHandler: .sqlite files
Submodules#
shapelib.core.handlers.flatgeobuf_handler module#
- class shapelib.core.handlers.flatgeobuf_handler.FlatGeobufHandler(path)[source]#
Bases:
GeoFileHandler- Parameters:
path (Path)
- validate_file()[source]#
Abstract method to validate the file according to specific handler requirements.
This method must be implemented by subclasses to perform custom validation (e.g., checking the file’s format or structure).
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- load_data(**kwargs)[source]#
Abstract method to load data from the geospatial file.
This method must be implemented by subclasses to load the contents of the file into memory or a data structure suitable for further operations.
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- Parameters:
kwargs (Any)
- create_obj(**kwargs)[source]#
Abstract method to create and return an object representing the file’s data.
This method must be implemented by subclasses to create and return an appropriate object that represents the file’s data, such as a GeoDataFrame or another custom object.
- Returns:
An object representing the data in the geospatial file.
- Return type:
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Parameters:
kwargs (Any)
shapelib.core.handlers.geo_file_handler module#
- class shapelib.core.handlers.geo_file_handler.GeoFileHandler(path)[source]#
Bases:
ABCAbstract base class for handling geospatial files.
This class provides a common interface for geospatial file handlers, including methods for loading data, validating files, and creating objects. Specific file handlers (e.g., for Shapefiles, GeoJSON, etc.) should inherit from this class and implement the required abstract methods.
- Variables:
driver (
str) – The driver used for handling the file, which must be defined in subclasses.extension (
str) – The file extension associated with the handler, which must be defined in subclasses.keep_z (
bool) – Whether the object created from the file keeps the Z coordinate of 3-D geometries. False by default; set by the factory fromread_file.
- Methods:
check_path() – Checks if the file path exists and is a file.
load_data() – Abstract method to load data from the geospatial file.
validate_file() – Abstract method to validate the file according to specific handler requirements.
create_obj() – Abstract method to create and return an object representing the file’s data.
- Parameters:
path (Path)
- check_path()[source]#
Check if the file path exists and is a file.
This method verifies whether the provided path exists and points to a valid file. If the file does not exist, it raises a FileNotFoundError.
- Raises:
FileNotFoundError – If the file does not exist or is not a file.
- Return type:
Examples
>>> handler = GeoFileHandler(path=Path("/path/to/file")) >>> handler.check_path() # Raises an error if the file is invalid
- create_geometry_instance(data, driver)[source]#
Create a geometry instance (Polygons, Lines, Points, or Empty) based on the most common geometry type in the GeoDataFrame.
Data read without a CRS is assumed to be WGS84 when its coordinates are lon/lat, and rejected otherwise (see
assume_wgs84_if_lonlat).- Parameters:
data (
GeoDataFrame) – The GeoDataFrame containing geometries.driver (
str) – The driver type (e.g., ‘GPKG’, ‘ESRI Shapefile’).
- Returns:
An instance of one of the geometry classes (Polygons, Lines, Points, or Empty).
- Return type:
- Raises:
ValueError – If the data has no CRS and its coordinates are not lon/lat.
- abstractmethod load_data()[source]#
Abstract method to load data from the geospatial file.
This method must be implemented by subclasses to load the contents of the file into memory or a data structure suitable for further operations.
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- abstractmethod validate_file()[source]#
Abstract method to validate the file according to specific handler requirements.
This method must be implemented by subclasses to perform custom validation (e.g., checking the file’s format or structure).
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- abstractmethod create_obj(**kwargs)[source]#
Abstract method to create and return an object representing the file’s data.
This method must be implemented by subclasses to create and return an appropriate object that represents the file’s data, such as a GeoDataFrame or another custom object.
- Returns:
An object representing the data in the geospatial file.
- Return type:
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Parameters:
kwargs (Any)
shapelib.core.handlers.geojson_handler module#
- class shapelib.core.handlers.geojson_handler.GeojsonHandler(path)[source]#
Bases:
GeoFileHandler- Parameters:
path (Path)
- validate_file()[source]#
Abstract method to validate the file according to specific handler requirements.
This method must be implemented by subclasses to perform custom validation (e.g., checking the file’s format or structure).
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- load_data(**kwargs)[source]#
Abstract method to load data from the geospatial file.
This method must be implemented by subclasses to load the contents of the file into memory or a data structure suitable for further operations.
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- Parameters:
kwargs (Any)
- create_obj(**kwargs)[source]#
Abstract method to create and return an object representing the file’s data.
This method must be implemented by subclasses to create and return an appropriate object that represents the file’s data, such as a GeoDataFrame or another custom object.
- Returns:
An object representing the data in the geospatial file.
- Return type:
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Parameters:
kwargs (Any)
shapelib.core.handlers.geopackage_handler module#
- class shapelib.core.handlers.geopackage_handler.GeopackageHandler(path)[source]#
Bases:
GeoFileHandlerA handler for GeoPackage (.gpkg) format.
This class provides functionality for reading and validating GeoPackage files using the GeoPandas library and GDAL for additional checks.
- Variables:
- Methods:
__init__(path) – Initializes the handler with a given GeoPackage path.
validate_file() – Validates the GeoPackage to ensure it exists, is non-empty, and can be opened by GDAL.
load_data(**kwargs) -> GeoDataFrame – Loads the GeoPackage as a GeoDataFrame.
create_obj(**kwargs) -> BaseShapes – Creates and returns an appropriate geometry object based on the contents of the GeoPackage.
- Parameters:
path (Path)
- validate_file()[source]#
Validate the GeoPackage file to ensure it exists, is non-empty, and can be opened by GDAL.
This method checks whether the file is empty based on file size and then tries to open the file with GDAL to confirm it is a valid GeoPackage.
- Raises:
ValueError – If the file is empty or cannot be recognized as a GeoPackage by GDAL.
GDALException – If GDAL encounters an error opening the file.
- Return type:
- load_data(**kwargs)[source]#
Load the GeoPackage using GeoPandas.
- Parameters:
**kwargs (
Any) – Additional keyword arguments to pass togeopandas.read_file(). For example, layer=”layer_name” if the GeoPackage has multiple layers.- Returns:
The loaded GeoDataFrame from the GeoPackage.
- Return type:
- create_obj(**kwargs)[source]#
Create an object representing the GeoPackage’s geometries based on the most common geometry type.
This method uses
create_appropriate_objfrom the base class to generate Polygons, Lines, Points, or an Empty geometry object.- Parameters:
**kwargs (
Any) – Additional keyword arguments passed toload_data().- Returns:
An instance of one of the geometry classes (Polygons, Lines, Points, or Empty), depending on the most common geometry type in the GeoPackage’s data.
- Return type:
shapelib.core.handlers.kml_handler module#
- class shapelib.core.handlers.kml_handler.KmlHandler(path)[source]#
Bases:
GeoFileHandler- Parameters:
path (Path)
- validate_file()[source]#
Abstract method to validate the file according to specific handler requirements.
This method must be implemented by subclasses to perform custom validation (e.g., checking the file’s format or structure).
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- load_data(**kwargs)[source]#
Abstract method to load data from the geospatial file.
This method must be implemented by subclasses to load the contents of the file into memory or a data structure suitable for further operations.
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- Parameters:
kwargs (Any)
- create_obj(**kwargs)[source]#
Abstract method to create and return an object representing the file’s data.
This method must be implemented by subclasses to create and return an appropriate object that represents the file’s data, such as a GeoDataFrame or another custom object.
- Returns:
An object representing the data in the geospatial file.
- Return type:
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Parameters:
kwargs (Any)
shapelib.core.handlers.shapefile_handler module#
- class shapelib.core.handlers.shapefile_handler.ShapefileHandler(path)[source]#
Bases:
GeoFileHandlerA handler for ESRI Shapefile (.shp) format.
This class provides functionality for reading, validating, and managing shapefiles using the Geopandas library. It attempts to load shapefiles with different encodings and handles exceptions related to file decoding.
- Variables:
- Methods:
load_data() – Loads the shapefile into a GeoDataFrame, trying different encodings.
validate_file() – Validates the shapefile to ensure it can be read.
create_obj() – Creates and returns a geometry object based on the shapefile’s contents.
- Parameters:
path (Path)
- encoding_list = ['utf-8', 'iso8859_15', 'latin1', 'cp1252', 'ascii']#
- engines = ['pyogrio', 'fiona']#
- load_data(**kwargs)[source]#
Attempt to load the shapefile using different encodings.
This method iterates over the encodings in encoding_list and attempts to read the shapefile using each encoding. If successful, the file is returned as a GeoDataFrame.
- Returns:
The loaded shapefile as a GeoDataFrame.
- Return type:
- Raises:
ValueError – If none of the encodings are able to decode the file.
- Parameters:
kwargs (Any)
Examples
>>> handler = ShapefileHandler(path=Path("/path/to/shapefile.shp")) >>> gdf = handler.load_data()
- validate_file()[source]#
Validate the shapefile to ensure it exists and is readable.
This method checks whether the shapefile and its associated files (e.g., .shx, .dbf) exist and can be read by GDAL.
- Raises:
FileNotFoundError – If the shapefile or one of its associated files (.shx, .dbf) is missing.
GDALException – If GDAL cannot read the shapefile or if the shapefile is invalid.
- Return type:
- check_empty_file()[source]#
Check if the shapefile is empty based on its file size.
This method checks if the shapefile is empty by evaluating its file size. Shapefiles that are exactly 100 bytes in size are considered empty.
- Returns:
The method prints a message if the file is empty.
- Return type:
Examples
>>> handler.check_empty_file() Empty Shapefile!
- check_missing_parts()[source]#
Check for the existence of essential auxiliary files associated with the shapefile.
This method checks if the following auxiliary files are missing: - .shx (shape index file) - .cpg (code page file for character encoding) - .dbf (attribute data file) - .prj (projection file)
If any of these files are missing, the corresponding handler method is invoked to handle the missing file.
- Returns:
The method invokes the handler methods if files are missing.
- Return type:
Examples
>>> handler.check_missing_parts()
- handle_missing_shx()[source]#
Attempt to recreate the missing .shx file using Fiona.
This method uses GDAL’s (via Fiona) to recreate the missing .shx file associated with the shapefile. GDAL’s ESRI Shapefile driver can regenerate the .shx when the configuration option SHAPE_RESTORE_SHX=YES is set.
- Raises:
RuntimeError – If the .shx file cannot be recreated, a RuntimeError is raised.
- Return type:
Examples
>>> handler.handle_missing_shx() Failed to recreate .shx file: [error message]
- handle_missing_cpg()[source]#
Handle the missing .cpg file by notifying the user.
The .cpg file specifies character encoding for the shapefile. While it is useful for ensuring correct character display, it is not mandatory for the core functionality of the shapefile. This method simply warns the user if the .cpg file is missing.
- Returns:
The method prints a warning message if the .cpg file is missing.
- Return type:
Examples
>>> handler.handle_missing_cpg() Missing .cpg. Ignoring it since it's not mandatory for the functionality of the Shapefile.
- handle_missing_dbf()[source]#
Handle the missing .dbf file by notifying the user.
The .dbf file holds attribute data (e.g., table data associated with the shapefile). While this information is useful, its absence does not prevent the shapefile from functioning. This method prints a warning message if the .dbf file is missing.
- Returns:
The method prints a warning message if the .dbf file is missing.
- Return type:
Examples
>>> handler.handle_missing_dbf() Missing .dbf. Ignoring it since it's not mandatory for the functionality of the Shapefile.
- handle_missing_prj()[source]#
Handle the missing .prj file by notifying the user.
The .prj file holds the shapefile’s CRS. Some producers leave it out (e.g. prescription maps exported for agricultural machinery), so its absence is not fatal here: the data is read without a CRS, and create_geometry_instance assumes WGS84 when the coordinates are lon/lat or raises a ValueError otherwise.
- Returns:
The method prints a notice if the .prj file is missing.
- Return type:
Examples
>>> handler.handle_missing_prj() Missing .prj. The CRS will be inferred from the coordinates (WGS84 if they are lon/lat).
- create_obj(**kwargs)[source]#
Create an object representing the shapefile’s geometries based on the most common type.
This method analyzes the most common geometry type in the shapefile and returns an appropriate object (Polygons, Lines, Points, or Empty). If the geometry type is not recognized, a TypeError may be raised.
- Returns:
A geometry object corresponding to the shapefile’s data, such as Polygons, Lines, Points, or Empty.
- Return type:
- Raises:
TypeError – If an unexpected geometry type is encountered.
- Parameters:
kwargs (Any)
Examples
>>> geom_obj = handler.create_obj() >>> isinstance(geom_obj, Polygons) True
shapelib.core.handlers.spatialite_handler module#
- class shapelib.core.handlers.spatialite_handler.SpatialiteHandler(path)[source]#
Bases:
GeoFileHandler- Parameters:
path (Path)
- validate_file()[source]#
Abstract method to validate the file according to specific handler requirements.
This method must be implemented by subclasses to perform custom validation (e.g., checking the file’s format or structure).
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- load_data(**kwargs)[source]#
Abstract method to load data from the geospatial file.
This method must be implemented by subclasses to load the contents of the file into memory or a data structure suitable for further operations.
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Return type:
- Parameters:
kwargs (Any)
- create_obj(**kwargs)[source]#
Abstract method to create and return an object representing the file’s data.
This method must be implemented by subclasses to create and return an appropriate object that represents the file’s data, such as a GeoDataFrame or another custom object.
- Returns:
An object representing the data in the geospatial file.
- Return type:
- Raises:
NotImplementedError – If the method is not implemented by a subclass.
- Parameters:
kwargs (Any)
shapelib.core.handlers.zipped_shapefile_handler module#
- class shapelib.core.handlers.zipped_shapefile_handler.ZippedShapefileHandler(path)[source]#
Bases:
GeoFileHandlerHandler for shapefiles stored inside a local .zip archive.
- Parameters:
path (Path)
- encoding_list = ['utf-8', 'iso8859_15', 'latin1', 'cp1252', 'ascii']#
- engines = ['pyogrio', 'fiona']#
- validate_file()[source]#
Validate that the archive is readable and contains at least one .shp file.
- Raises:
ValueError – If the archive is invalid or contains no shapefile.
- Return type:
- load_data(**kwargs)[source]#
Load geospatial data from ZIP, trying engines and encodings.
- Parameters:
**kwargs (
Any) – Additional arguments passed togeopandas.read_file.- Returns:
Loaded geospatial data.
- Return type:
- Raises:
ValueError – If a mandatory component is missing from the archive, or if loading fails across all engine and encoding combinations. The last underlying error is included in the message and chained.