改善
Kaizen  · Today I Learned by Ville Säävuori

Using Spatialite With Django on MacOS

Note! This doesn’t seem to work on macOS Sequoia. Here’s an updated version.


I’ve been working on several GeoDjango projects latey and one thing common with most of them is the difficulty of setting up Spatialite on CI and macOS. The usual error message from pytest is:

django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading.

The error happens because Python is built with extensions loading disabled.

For macOS the easiest way to use Spatialite is to use Homebrew to install the Spatialite deps and then use pyenv to install a compatible Python.

Step By Step

First install Spatialite:

brew install spatialite-tools

Then check where the related libraries are installed:

brew info sqlite

brew brew --prefix openssl

Then set LDFLAGS, CPPFLAGS and PYTHON_CONFIGURE_OPTS before installing a Python version where --enable-loadable-sqlite-extensions is turned on:

LDFLAGS="-L/opt/homebrew/opt/sqlite/lib" CPPFLAGS="-I/opt/homebrew/opt/sqlite/include" PYTHON_CONFIGURE_OPTS="--enable-loadable-sqlite-extensions --enable-optimizations --with-openssl=/opt/homebrew/opt/openssl@3" pyenv install 3.11.6

Now just recreate your virtualenv using this Python version!