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

本地正常的GCP Cloud Function云端部署后文件上传失败排查

问题分析与解决方案
  • 云端Cloud Function运行在GCP托管的服务器环境中,完全无法访问你本地电脑的C盘,这是部署后报错FileNotFound的根本原因。本地运行时代码在你的机器上执行,能读取C盘文件;但部署到云端后,代码在GCP的服务器里运行,不存在C:\\dev\\这类本地路径。

正确流程调整

要实现你的需求,必须拆分执行环节:

  1. 本地→GCS:在本地环境单独执行文件上传到GCS的操作(不要放到云端Function中)
  2. 云端处理:Cloud Function仅负责从GCS读取文件、执行格式转换、将结果写回GCS
  3. GCS→本地:在本地环境单独执行从GCS下载处理后文件的操作(同样不要放到云端Function中)

代码修改示例

1. 云端Cloud Function代码(仅保留GCS处理逻辑)

import functions_framework
from google.cloud import storage
import pandas as pd
import fastparquet

@functions_framework.http
def pandas_processing(request):
    client = storage.Client()
    bucket_name = 'gcp-python-files'

    # 从GCS读取CSV文件
    try:
        df = pd.read_csv(f'gs://{bucket_name}/drinks.csv', encoding='utf-8')
    except Exception as e:
        return f"读取文件错误: {str(e)}", 500
              
    print("CSV文件表头:\n", df.head(3))
    
    # 将转换后的Parquet文件写回GCS
    df.to_parquet(f'gs://{bucket_name}/drinks.parquet', engine='fastparquet')
    print("Parquet文件已导出至Bucket")

    return '处理完成,结果已保存至GCS'

# list_buckets、hello_world等辅助函数可按需保留

2. 本地环境执行的上传/下载脚本(单独运行,无需部署)

from google.cloud import storage
import requests

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(source_file_name)
    print(f"文件 {source_file_name} 已上传至 {destination_blob_name}")

def download_blob(bucket_name, source_blob_name, destination_file_name):
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(source_blob_name)
    blob.download_to_filename(destination_file_name)
    print(f"已从Bucket下载 {source_blob_name} 至本地 {destination_file_name}")

# 1. 本地执行文件上传到GCS
upload_blob('gcp-python-files', 'C:\\dev\\drinks.csv', 'drinks.csv')

# 2. 触发云端Cloud Function进行处理
function_url = "你的Cloud Function HTTP触发URL"
response = requests.get(function_url)
print(response.text)

# 3. 本地执行结果文件下载
download_blob('gcp-python-files', 'drinks.parquet', 'c:\\dev\\drinks.parquet')

权限注意事项

  • 确保Cloud Function使用的默认服务账号(PROJECT_ID@appspot.gserviceaccount.com)拥有GCS Bucket的storage.objects.read和storage.objects.write权限
  • 本地脚本执行前,需通过gcloud auth application-default login完成认证,或配置GOOGLE_APPLICATION_CREDENTIALS环境变量指向服务账号密钥文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:14:55