Using SQLAlchemy with Spatial Databases
npx @tessl/cli install tessl/pypi-geoalchemy2@0.18.0A comprehensive Python toolkit that provides a SQLAlchemy extension for working with spatial databases. GeoAlchemy2 enables seamless integration of geographic and spatial data types, functions, and operations into SQLAlchemy-based applications, supporting major spatial database backends including PostGIS (PostgreSQL), SpatiaLite (SQLite), MySQL, and MariaDB.
pip install GeoAlchemy2pip install GeoAlchemy2[shapely] for Shapely integrationimport geoalchemy2
from geoalchemy2 import Geometry, Geography, Raster
from geoalchemy2 import WKTElement, WKBElement, RasterElement
from geoalchemy2 import functions as func
from geoalchemy2.shape import to_shape, from_shape # Requires shapelyfrom sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from geoalchemy2 import Geometry, Geography, functions as func
from geoalchemy2 import WKTElement
Base = declarative_base()
class Lake(Base):
__tablename__ = 'lake'
id = Column(Integer, primary_key=True)
name = Column(String)
geom = Column(Geometry('POLYGON', srid=4326))
# Create engine and session
engine = create_engine('postgresql://user:pass@localhost/gis_db')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Insert data with WKT
lake = Lake(
name='Example Lake',
geom=WKTElement('POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))', srid=4326)
)
session.add(lake)
session.commit()
# Query with spatial functions
lakes = session.query(Lake).filter(
func.ST_Area(Lake.geom) > 1000
).all()
# Use spatial relationships
nearby_lakes = session.query(Lake).filter(
func.ST_DWithin(Lake.geom, WKTElement('POINT(0.5 0.5)', srid=4326), 1000)
).all()GeoAlchemy2 extends SQLAlchemy's type system and function capabilities to provide comprehensive spatial database support:
Define spatial columns in SQLAlchemy models using Geometry, Geography, and Raster types with support for all major spatial databases and automatic spatial indexing.
class Geometry:
def __init__(
geometry_type: str = "GEOMETRY",
srid: int = -1,
dimension: int = None,
spatial_index: bool = True,
use_N_D_index: bool = False,
use_typmod: bool = None
): ...
class Geography:
def __init__(
geometry_type: str = "GEOMETRY",
srid: int = -1,
dimension: int = None,
spatial_index: bool = True,
use_N_D_index: bool = False,
use_typmod: bool = None
): ...
class Raster:
def __init__(
spatial_index: bool = True,
nullable: bool = True
): ...Handle spatial data interchange with WKT, WKB, and Raster elements that provide transparent conversion between database representations and Python objects.
class WKTElement:
def __init__(data: str, srid: int = -1, extended: bool = None): ...
class WKBElement:
def __init__(data: bytes, srid: int = -1, extended: bool = None): ...
class RasterElement:
def __init__(data: bytes, srid: int = -1): ...Access to 376+ spatial functions covering geometry construction, spatial relationships, measurements, transformations, and analysis operations.
# Geometry construction
def ST_MakePoint(x: float, y: float, z: float = None, m: float = None): ...
def ST_MakeLine(*points): ...
def ST_MakePolygon(shell, holes=None): ...
# Spatial relationships
def ST_Contains(geom1, geom2): ...
def ST_Within(geom1, geom2): ...
def ST_Intersects(geom1, geom2): ...
# Measurements
def ST_Area(geom): ...
def ST_Length(geom): ...
def ST_Distance(geom1, geom2): ...Convert between GeoAlchemy2 spatial elements and Shapely geometries for advanced geometric operations and analysis.
def to_shape(element: Union[WKBElement, WKTElement]): ...
def from_shape(shape, srid: int = -1, extended: bool = None): ...Manage spatial databases with automatic DDL event handling, spatial index creation, and dialect-specific optimizations.
def setup_ddl_event_listeners(): ...
def load_spatialite(dbapi_conn, *args): ...
def load_spatialite_gpkg(dbapi_conn, *args, **kwargs): ...
class GeoEngine: ...Integrate spatial schema changes with Alembic migrations using specialized operations for spatial columns, tables, and indexes.
class AddGeospatialColumnOp: ...
class DropGeospatialColumnOp: ...
class CreateGeospatialTableOp: ...
class DropGeospatialTableOp: ...GeoAlchemy2 defines specific exceptions for spatial operations:
class ArgumentError(Exception):
"""Raised when an invalid or conflicting function argument is supplied."""