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云工具冲突:
- 创建虚拟环境:
python -m venv venv - 激活环境:
source venv/bin/activate(Linux/macOS)或venv\Scripts\activate(Windows) - 安装指定版本:
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
相关产品推荐
相关产品推荐

