M1 Mac - GDAL 错误架构错误 [Django]

M1 Mac - GDAL Wrong Architecture Error [Django]

我正在尝试启动和 运行ning 一个 django 项目,这取决于 GDAL 库。我正在研究基于 mac.

的 M1

按照 official Django docs 上的说明,我已经通过 brew 安装了必要的软件包

$ brew install postgresql
$ brew install postgis
$ brew install gdal
$ brew install libgeoip

gdalinfo --version 运行 很好,显示版本为 3.3.1

gdal-config --libs returns 这个路径:-L/opt/homebrew/Cellar/gdal/3.3.1_2/lib -lgdal

符号链接也放在自制程序的 lib 目录中,它在我的路径环境变量中。

当我在不指定 gdal 库路径的情况下尝试 运行 django 时,它抱怨找不到 GDAL 包(即使该库可以访问,因为它的符号链接可以通过路径 env 获得变量)。

当我尝试使用 GDAL_LIBRARY_PATH 指定 GDAL 库的路径时,出现此错误:

OSError: dlopen(/opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib, 6): no suitable image found.  Did find:
    /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib: mach-o, but wrong architecture
    /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.29.dylib: mach-o, but wrong architecture

P.s。我已经看过 this answer,但没有帮助。

当我尝试 运行 gdalinfo 时,它 运行 很好,但是当 django 尝试 运行 时,它会抛出这个错误吗?我做错了什么?

尝试使用新的 arm 版本 python!

brew install --cask miniforge
conda init zsh
conda activate
conda install numpy scipy scikit-learn

GDAL 和 Python 可能是为不同的 CPU 架构编译的。在 M1 系统上,OS 可以 运行 本机 arm64 和模拟 x86_64 二进制文件。

要检查:运行 file /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylibfile $(which python3),应该显示两者支持的 CPU 架构。

如果两者不匹配,您将不得不重新安装其中之一。请注意,如果您重新安装 Python,您还必须重新安装所有带有 C 扩展的 Python 包。

如果您在 M1 上本机 运行 不需要这个,请考虑使用 Linux 虚拟 Machine。

我对这个问题的最终解决方案是在我的 M1 Mac 上使用 Canonical 的 Multipass 创建一个 Ubuntu VM,然后安装 postgresql、postgis 和所有相关依赖项,包括 GDAL,就像 Linux.

https://multipass.run/

我使用以下安装 postgres 和 postgis:

sudo apt-get install libpq-dev #required for psycop2-binary installation
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

sudo apt-get -y install postgresql-13 #or other version number

sudo apt install postgis postgresql-13-postgis-3

sudo -i -u postgres
createuser yourusername
createdb postgis_db -O yourusername #create your db
psql -d postgis_db
CREATE EXTENSION postgis;

#make sure these are all installed:

sudo apt-get install binutils libproj-dev 
sudo apt-get install gdal-bin
sudo apt-get install libgeos++
sudo apt-get install proj-bin

我通过 VSCode SSH 进入 ubuntu VM 并照常开发 django。有一篇关于 Multipass 设置的好文章 here.

我在 M1 上使用此设置没有遇到任何问题。

更新:截至 2022 年 1 月 10 日,Monterey 12.1 上的 MacOS 防火墙存在一些问题,无法很好地与 Multipass 配合使用。这是一个 open issue on GitHub,Canonical 正在研究它。

更新 #2:截至 2022 年 4 月,MacOS 防火墙的多通道问题似乎已解决,这是在 Apple 的最新 OS 更新之后。

我偶然发现了同样的问题,在我的情况下,通过在 settings.py 中添加 GDAL_LIBRARY_PATH 解决了这个问题,而且 GEOS_LIBRARY_PATH

GDAL_LIBRARY_PATH = '/opt/homebrew/Cellar/gdal/3.4.1_1/lib/libgdal.dylib'
GEOS_LIBRARY_PATH = '/opt/homebrew/Cellar/geos/3.10.2/lib/libgeos_c.1.16.0.dylib'