将Kivy应用转为APK时psycopg2 SSL支持异常问题
问题本质
你碰到的psycopg2.OperationalError: sslmode value "verify full" invalid when SSL support is not compiled in错误,核心原因是psycopg2在Android环境编译时未链接SSL库,导致无法处理带SSL验证的数据库连接配置。
修复步骤
1. 调整python-for-android依赖配置
修改requirements列表,确保依赖顺序和关联正确:
python3==3.7.6 hostpython3==3.7.6 android openssl postgres pyopenssl httplib2 setuptools Cython==0.29.10 sdl2_ttf==2.0.15 pillow certifi typing typing_extensions sh pyjnius backports.zoneinfo psycopg2==2.9.5 kivy==2.0.0 kivymd==1.0.1
注意将openssl放在postgres前,让python-for-android先编译SSL库,再让postgres编译时自动链接它。
2. 添加psycopg2编译环境变量
在GitHub workflow的打包步骤前,设置环境变量强制psycopg2编译时启用SSL,并指向Android平台的SSL库:
export PYCFLAGS="-I$ANDROID_BUILD_TOP/openssl/include" export PYLIBS="-L$ANDROID_BUILD_TOP/openssl/lib -lssl -lcrypto" export PSYCOPG2_BUILD_SSL=1
这些变量会告诉psycopg2的编译脚本,使用Android环境下的SSL库而非宿主Ubuntu的库。
3. 简化宿主环境依赖安装
你之前重复安装了部分依赖,可简化为以下命令,确保必备的编译工具、SSL和postgres开发库都已安装:
sudo apt-get install -y build-essential ccache git zlib1g-dev python3-dev libncurses5:i386 libstdc++6:i386 zlib1g:i386 openjdk-8-jdk unzip ant autoconf libtool libssl-dev libpq-dev openssl
4. 清理编译缓存
避免旧的未带SSL的依赖缓存被复用,打包前执行清理:
python-for-android clean_dists python-for-android clean_builds
强制重新编译所有依赖,确保postgres和psycopg2都正确链接SSL。
5. 临时验证(可选)
如果以上步骤仍有问题,可临时将数据库连接的sslmode改为require,验证是否是SSL编译问题导致的崩溃。但这只是临时测试,最终还是要解决编译问题以支持完整的SSL验证。
核心原理
python-for-android编译第三方库时不会自动继承宿主系统的SSL配置,必须明确让postgres依赖openssl,并通过环境变量告知psycopg2编译时使用Android平台的SSL库。之前的问题大概率是postgres编译时未链接SSL,或psycopg2未启用SSL编译选项。
内容的提问来源于stack exchange,提问作者Si110n

