You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Cloud Functions中mysql.connector导入及依赖冲突求助

Google Cloud Functions中MySQL连接的依赖与导入问题解决

一、替换正确的MySQL连接包

你之前使用的mysql_connector_repackaged是非官方的老旧包,这是引发导入错误的核心原因:

  • 直接删除requirements.txt里的mysql_connector_repackaged==0.3.1,替换为官方维护的包:mysql-connector-python==8.0.28
  • 代码里保留import mysql.connector,不要只导入mysql——官方包才会提供mysql.connector模块,直接解决AttributeError问题

二、解决protobuf版本冲突

Google Cloud Functions的基础运行环境自带兼容的protobuf版本,无需手动调整:

  • 不要在requirements.txt里指定protobuf版本,让云环境自动匹配依赖
  • 本地测试时,用虚拟环境隔离依赖,避免和全局的Google云工具冲突:
    1. 创建虚拟环境:python -m venv venv
    2. 激活环境:source venv/bin/activate(Linux/macOS)或venv\Scripts\activate(Windows)
    3. 安装指定版本:pip install mysql-connector-python==8.0.28

三、部署注意事项

  • 选择Python 3.9或3.10作为Cloud Functions的运行时,兼容性更稳定
  • 不要在Cloud Shell全局安装依赖,直接通过requirements.txt让平台自动安装,避免破坏环境
  • 连接代码保持原有写法即可:
connection = mysql.connector.connect(
    host="你的数据库主机地址",
    user="数据库用户名",
    password="数据库密码",
    database="目标数据库名"
)

内容的提问来源于stack exchange,提问作者Devin Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:55:12