python - Google App Engine - 在单独的项目中使用 Google Cloud Storage,项目名称中有特殊字符

标签 python google-app-engine google-cloud-storage

我正在尝试在单独的项目中从 GAE (Python) 应用程序读取和写入 GCS 存储桶。另一个项目:

  • 已设置结算
  • 已向 GAE 应用尝试写入的存储桶上的服务帐户授予写入权限。

但是,我无法从我的 GAE 应用程序写入存储桶。该项目(我没有设置)的项目 ID 中有一个冒号 (:),并且我收到错误 ValueError: Path should have format/bucket/filename...

我尝试使用项目 ID 的 url 转义版本(即在存储桶路径的第一段中),但得到了相同的错误。

我还尝试使用项目编号作为路径的第一段,但随后它找不到存储桶:NotFoundError: Expect status [201] from Google Storage。但状态为 404。

是否可以引用这样的存储桶?我需要以某种方式使用 x-goog-project-id header 吗?

<小时/>

编辑:GCS 适配器代码

请注意,存储桶设置为从配置文件中读取,它最终类似于Uploader('my:gcs-project/folder')。由于收到错误消息,我确信它设置正确。

import os.path
import cloudstorage as gcs

class Uploader():

  def __init__(self,bucket):
    self._bucket = bucket
    self._path   = ''
    self._meta   = {}
    self._type   = None

  def datasend(self, id):
    self._path = id
    return self

  def description(self, _):
    self._meta['x-goog-meta-desc'] = _
    return self

  def type(self, _):
    self._type = _
    return self

  def fullpath(self, filename):
    return "/".join([
             part for part in [
               "", self._bucket, self._path, os.path.basename(filename)
             ] if not (part is None)
           ])

  def __call__(self, file):
    self.upload(file)

  def upload(self, file):
    gcs_file = None
    try:
      gcs_file = gcs.open( self.fullpath(file.filename),
                           'w',
                           content_type=self._type,
                           options=self._meta
                         )
      for chunk in fbuffer(file.file):
        gcs_file.write(chunk)

    finally:
      if gcs_file:
        gcs_file.close()

def fbuffer(f, size=10240):
  while True:
    chunk = f.read(size)
    if not chunk: break
    yield chunk

最佳答案

尝试用这样的东西来获取你的水桶:

bucket_name = os.environ.get('BUCKET_NAME', app_identity.get_default_gcs_bucket_name())
bucket = '/' + bucket_name
filename = bucket + '/' + "myfile.jpg"

关于python - Google App Engine - 在单独的项目中使用 Google Cloud Storage,项目名称中有特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26130906/

相关文章:

python - Bash 中任何等效的 * 样式,用于作用于不匹配相同模式的多个文件

android - Google App Engine - Cloud Endpoints - 未设置应用程序名称

google-cloud-platform - 在两个谷歌云项目之间复制数据以及以数据为中心的环境中 DEV & PROD 环境的最佳实践

python - 在 GAE 中将 python 类存储为 pickle ?

python - AppEngine/OS X - vendor.add ('lib' ) 只是不工作? (加上部分解决方案)

google-cloud-storage - 使用 GCS 签名的 url 发送元数据

google-cloud-platform - 将大型 csv 直接加载到 Bigquery 中,无需云存储?

python - 使用 Python 在 Visual Studio Code 中调试不起作用

python - 在 Bash 调用中处理特定的 Python 错误?

python - 如何使用pandas groupby向每个组添加一行?