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

Google Storage读写文件遇NotFoundError(404)错误求助

Google Cloud Storage 404 NotFoundError 读写失败排查与解决

看起来你在使用GCS旧客户端库进行读写操作时遇到了404错误,我来帮你梳理几个关键排查点和修复方案:

1. 先确认路径与存储桶名称的正确性

从报错信息来看,代码尝试访问的路径是/bucket-name-12345.appspot.com/test,但你要读取的是test.txt,这里首先要检查:

  • 代码中filename1的拼接是否正确:你当前的写法是bucket + '/test.txt',而bucket是'/' + bucket_name,最终路径应该是/bucket-name-12345.appspot.com/test.txt,但报错里少了.txt后缀,是不是代码里某个地方写错了文件名?
  • 确保bucket_name对应的存储桶确实存在于你的GCS中,检查名称拼写(包括大小写、后缀),GCS存储桶名称是全局唯一且严格匹配的。
  • 可以在代码中添加日志输出实际使用的存储桶和文件路径,确认没有拼接错误:
    log.info(f"Using bucket: {bucket_name}")
    log.info(f"Reading file path: {filename1}")
    

2. 验证环境变量配置

你用os.environ.get('BUCKET_NAME', '默认桶名')获取存储桶名称,如果环境变量BUCKET_NAME没有正确设置,代码会使用默认值。请确认:

  • 部署环境(比如App Engine)中是否已经配置了BUCKET_NAME环境变量,值为你的实际存储桶名称
  • 如果使用默认值,确认这个默认桶名是你已经创建的存储桶

3. 检查权限配置

虽然你提到配置了所有者权限,但要确认运行代码的服务账号拥有足够的GCS权限:

  • 如果是在App Engine上运行,默认服务账号是你的项目ID@appspot.gserviceaccount.com,需要在GCS控制台的存储桶权限设置中,给这个账号添加Storage Object Viewer(读权限)和Storage Object Creator(写权限)
  • 如果是本地测试,确保你使用的凭据(比如service account key)拥有对应的GCS权限

4. 考虑升级到官方推荐的客户端库

你当前使用的cloudstorage是旧版的App Engine GCS客户端库,现在官方推荐使用google-cloud-storage库,它的API更清晰,也更少出现路径相关的问题。这里给你改写一段兼容的代码示例:

from google.cloud import storage
import os
import logging

log = logging.getLogger(__name__)

def get_cloudstorage(self, site, start_date):
    bucket_name = os.environ.get('BUCKET_NAME', 'bucket-name-12345.appspot.com')
    log.info(" in the cloud storage get method")
    
    # 初始化GCS客户端
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    
    # 写入文件到GCS
    self.create_file(bucket, 'sample')
    # 读取GCS中的test.txt文件
    self.read_file(bucket, 'test.txt')

def create_file(self, bucket, blob_name):
    """Create a file in Cloud Storage using the new client library"""
    log.info(" in the cloud storage create_file method")
    blob = bucket.blob(blob_name)
    # 写入内容,同时设置元数据
    blob.upload_from_string(
        'abcde\n' + 'f'*1024*4 + '\n',
        content_type='text/plain',
        metadata={'foo': 'foo', 'bar': 'bar'}
    )
    self.tmp_filenames_to_clean_up.append(blob_name)
    log.info(" end of the create method ")

def read_file(self, bucket, blob_name):
    """Read a file from Cloud Storage using the new client library"""
    blob = bucket.blob(blob_name)
    if not blob.exists():
        log.error(f"File {blob_name} not found in bucket {bucket.name}")
        return
    # 读取最后1024个字符
    content = blob.download_as_text()
    log.info(content[-1024:])
    log.info('end of the read_file ')

最后一步:确认文件存在

登录GCS控制台,检查test.txt是否确实在存储桶的根目录下,而不是放在某个子文件夹中,确保文件路径和代码中指定的完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:08:25