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

Cloud Run函数上传文件至Cloud Storage遇500错误的排查求助

Cloud Run函数上传Cloud Storage时出现500错误的排查与解决

我是谷歌云新手及初级开发者,正在搭建一套自动化系统:通过Cloud Schedule触发Cloud Run函数生成图表并保存为JPEG格式至Cloud Storage Bucket,该操作将触发另一Cloud Run函数调用Klaviyo API发送邮件。目前第二个函数可正常运行,但第一个函数上传文件时出现500错误。

错误详情

  • Google Cloud Scheduler返回POST 500响应,请求地址为https://generate-and-upload-1017454958754.us-central1.run.app/,调试信息显示URL_UNREACHABLE-UNREACHABLE_5xx. Original HTTP response code number = 500;
  • 代码输出提示Error: your-image-bucket-name environment variable not set。

第一个Cloud Run函数代码

import functions_framework
from google.cloud import storage
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import io
import os
from datetime import datetime


def generate_image_bytes():
    """Generates a random line graph as JPEG bytes."""
    try:
        num_points = 20
        data = {
            'X': np.arange(num_points),
            'Y1': np.random.rand(num_points) * 10,
            'Y2': np.random.rand(num_points) * 15 + 5,
            'Y3': np.random.randn(num_points) * 5,
        }
        df = pd.DataFrame(data)

        plt.figure(figsize=(10, 6))
        plt.plot(df['X'], df['Y1'], label='Data Series 1', marker='o')
        plt.plot(df['X'], df['Y2'], label='Data Series 2', marker='x')
        plt.plot(df['X'], df['Y3'], label='Data Series 3', marker='+')
        plt.xlabel("X-axis")
        plt.ylabel("Y-axis Value")
        plt.title("Automated Line Graph")
        plt.legend()
        plt.grid(True)

        buffer = io.BytesIO()
        plt.savefig(buffer, format='jpeg', dpi=300, bbox_inches='tight')
        buffer.seek(0)
        plt.close()
        return buffer.getvalue()
    except Exception as e:
        print(f"Error generating image: {e}")
        return None

@functions_framework.http
def generate_and_upload(request):
    """Generates an image and uploads it to Cloud Storage."""
    bucket_name = os.environ.get("your-image-bucket-name")
    if not bucket_name:
        error_message = "Error: your-image-bucket-name environment variable not set."
        print(error_message)
        return error_message, 500

    image_bytes = generate_image_bytes()
    if image_bytes:
        client = storage.Client()
        bucket = client.bucket(bucket_name)
        filename = f"automated_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpeg"
        blob = bucket.blob(filename)
        try:
            blob.upload_from_string(image_bytes, content_type="image/jpeg")
            upload_message = f"Image uploaded to gs://{your-image-bucket-name}/{filename}"
            print(upload_message)
            return upload_message, 200
        except Exception as e:
            error_message = f"Error during upload: {e}"
            print(error_message)
            return error_message, 500
    else:
        error_message = "Image generation failed."
        print(error_message)
        return error_message, 500

我接触的资料大多针对Google Cloud Functions,对Cloud Run的配置细节不熟悉,不知道如何解决这个问题,请求帮助。


解决方案

1. 修复代码变量引用错误

上传成功的消息中,直接使用了未定义的字符串your-image-bucket-name,需替换为已获取的bucket_name变量:

upload_message = f"Image uploaded to gs://{bucket_name}/{filename}"

2. 配置Cloud Run环境变量

根据错误提示,需为Cloud Run服务添加缺失的环境变量:

  • 进入谷歌云控制台的Cloud Run服务列表,找到generate-and-upload服务;
  • 点击编辑与部署新版本;
  • 展开环境变量模块,添加键为your-image-bucket-name、值为你的Cloud Storage Bucket名称的条目;
  • 点击部署完成更新。

3. 配置Cloud Run服务权限

确保Cloud Run使用的服务账号拥有Cloud Storage写入权限:

  • 进入Cloud Run服务详情页的权限标签;
  • 找到服务默认使用的服务账号(格式通常为PROJECT_NUMBER-compute@developer.gserviceaccount.com);
  • 为该账号添加Storage Object Creator或Storage Admin角色(优先选择最小权限的Storage Object Creator);
  • 保存权限设置。

4. 测试验证

配置完成后,直接访问Cloud Run服务URL或通过Cloud Scheduler重新触发任务,检查是否返回200成功响应,同时查看Cloud Storage Bucket是否生成目标图片文件。

内容的提问来源于stack exchange,提问作者Amy Lock

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:47:10