GAE Django项目升级Python3.10后本地开发故障解决咨询
问题描述
将Google App Engine上的Django项目从Python 2.7升级至Python 3.10后,生产环境运行正常,但本地开发无法访问Datastore:
- 执行
python manage.py runserver能启动服务器,但访问Datastore时提示:
ERROR 2023-10-12 10:56:46,886 [exception:88] Could not import googledatastore. This library must be installed with version >= 6.0.0 to use the Cloud Datastore API. ... google.appengine.api.datastore_errors.BadArgumentError: Could not import googledatastore. This library must be installed with version >= 6.0.0 to use the Cloud Datastore API.
- 安装
googledatastore==7.0.2后,出现Python 2语法错误:
Exception in thread django-main-thread: ... File "/home/user_name/backend.worktrees/Python3/project_name/sitepackages/dev/googledatastore/helper.py", line 406 _MICROS_PER_SECOND = 1000000L ^ SyntaxError: invalid decimal literal
项目配置信息
- app.yaml:
runtime: python310 app_engine_apis: true entrypoint: gunicorn project_name.wsgi:application -b :$PORT -w 8 -t 600 instance_class: F4 handlers: - url: /internal/.* script: auto secure: always login: optional - url: /static static_dir: static/ secure: always - url: /.* script: auto secure: always
- requirements.txt:
django-cors-headers==4.2.0 djangorestframework==3.14.0 djangorestframework-jwt==1.11.0 Pillow==10.0.0 line-bot-sdk==3.1.0 requests-toolbelt==0.10.1 qrcode==7.4.2 xmltodict==0.13.0 icecream==2.1.3 google-cloud-logging==3.5.0 google-cloud-storage==2.10.0 google-cloud-secret-manager==2.16.2 more_itertools==9.1.0 elasticsearch==7.17.9 elasticsearch-dsl==7.4.1 chardet==5.1.0 djangae==2.0.0rc2 django-gcloud-connectors==0.4.0 django==3.2.20 django-csp==3.7 django-session-csrf==0.7.1 six==1.16.0 # legacy bundled services for python3 appengine-python-standard==1.1.2 # web server (entrypoint) gunicorn==20.1.0 # temporary fix for build error: AttributeError: cython_sources pyyaml==5.3.1
注:依赖包安装在sitepackages/dev/和sitepackages/prod/目录,运行时添加至PATH。
解决方案
1. 移除googledatastore依赖,使用官方Datastore模拟器
googledatastore是Python 2遗留库,完全不兼容Python 3。Python 3环境下必须用Cloud Datastore Emulator做本地开发:
- 安装并启动模拟器:
gcloud components install cloud-datastore-emulator gcloud beta emulators datastore start --project=你的项目ID - 启动本地服务器前设置环境变量:
export DATASTORE_EMULATOR_HOST=localhost:8081 export DATASTORE_PROJECT_ID=你的项目ID
2. 清理并重建依赖目录
当前sitepackages/dev/可能混入了Python 2版本的库,导致语法错误:
- 清空
sitepackages/dev/目录 - 重新安装Python 3兼容的依赖到生产目录:
pip install -r requirements.txt --target sitepackages/prod/ - 本地开发时仅加载
sitepackages/prod/路径,避免dev/目录干扰
3. 确认App Engine API配置正确性
appengine-python-standard已包含Python 3访问App Engine APIs的组件,无需额外依赖。检查settings.py中的数据库配置:
DATABASES = { 'default': { 'ENGINE': 'django_gcloud_connectors.datastore', 'PROJECT_ID': '你的项目ID', } }
4. 替换旧API调用(若有)
如果代码中直接调用了googledatastore,替换为Python 3兼容的官方库:
- 在
requirements.txt添加:google-cloud-datastore==2.15.0 - 修改代码中的导入语句:
# 替换 from googledatastore import ... from google.cloud import datastore
内容的提问来源于stack exchange,提问作者sqf
相关产品推荐
相关产品推荐

