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

Google Cloud App Engine部署FastAPI遇502错误:mysql模块缺失

解决GAE部署FastAPI应用时的ModuleNotFoundError: No module named 'mysql'问题

问题诊断

从日志可见,部署到Google Cloud App Engine后,Python无法找到mysql模块——尽管本地运行正常,且requirements.txt中已声明mysql-connector-python==8.0.32。以下是针对性解决步骤:

解决步骤

1. 修复依赖配置与运行时兼容性

  • 检查requirements.txt,确保mysql-connector-python==8.0.32一行左对齐、无前缀空格、无拼写错误。
  • Python 3.7 runtime已被Google Cloud终止支持,建议升级到更高版本(如Python 3.10):
    • 修改app.yaml的运行时配置:
      runtime: python310
      entrypoint: gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
      
    • 更新requirements.txt到兼容新版本Python的依赖版本,示例:
      fastapi>=0.100.0
      gunicorn>=21.2.0
      uvicorn>=0.23.2
      mysql-connector-python==8.2.0
      pydantic>=2.0.0
      

2. 替换MySQL驱动(可选但推荐)

若mysql-connector-python仍无法正常安装,可改用对GAE环境支持更稳定的mysqlclient:

  • 修改requirements.txt,替换为:
    mysqlclient==2.2.0
    
  • 调整代码中的导入与连接逻辑:
    from fastapi import FastAPI
    import MySQLdb
    
    app = FastAPI()
    
    @app.get("/")
    def home():
        success = ""
        try:
            mydb = MySQLdb.connect(
                host="***",
                user="***",
                password="***",
                database="dbname"  # 明确指定数据库,避免SQL拼写错误
            )
            cursor = mydb.cursor()
            sql = "INSERT INTO `tablename` (`Email`, `FirstName`, `LastName`) VALUES ('johndoe@example.com', 'John', 'Doe')"
            cursor.execute(sql)
            mydb.commit()
            success = "yes"
        except Exception as e:
            if 'mydb' in locals():
                mydb.rollback()
            print(f"Error occurred: {str(e)}")
        finally:
            if 'mydb' in locals():
                mydb.close()
        return {"message": "Hello World " + success}
    

3. 修正模块级数据库连接的问题

原代码在模块级别初始化数据库连接,在GAE多worker环境下会导致连接泄漏或失效。建议将连接逻辑移至请求处理内部,或用依赖注入管理连接生命周期:

from fastapi import FastAPI, Depends
import mysql.connector

app = FastAPI()

def get_db_connection():
    conn = mysql.connector.connect(
        host="***",
        user="***",
        password="***",
        database="dbname"
    )
    try:
        yield conn
    finally:
        conn.close()

@app.get("/")
def home(db=Depends(get_db_connection)):
    success = ""
    cursor = db.cursor()
    sql = "INSERT INTO `tablename` (`Email`, `FirstName`, `LastName`) VALUES ('johndoe@example.com', 'John', 'Doe')"
    try:
        cursor.execute(sql)
        db.commit()
        success = "yes"
    except Exception as e:
        db.rollback()
        print(f"Error: {str(e)}")
    return {"message": "Hello World " + success}

4. 重新部署并验证

  • 清理本地依赖缓存,重新生成requirements.txt:
    pip freeze > requirements.txt
    
  • 使用gcloud工具重新部署,查看部署日志确认依赖安装状态:
    gcloud app deploy --verbosity=debug
    

额外注意事项

  • 原SQL语句中的dbnae疑似拼写错误,需改为实际数据库名称。
  • 若使用Google Cloud SQL,需确保实例已允许GAE服务访问,或数据库主机地址可被GAE环境解析。

内容的提问来源于stack exchange,提问作者harshit gupta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:04:56