python - 无法使用 Google 云存储将文件保存到存储桶。可以在服务器上运行,但不能在本地运行

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

我正在尝试使用以下代码将文件保存到云存储。

    bucket_name = app_identity.get_default_gcs_bucket_name()
    uploaded_file = self.request.POST.get('uploaded_file')
    file_name = getattr(uploaded_file, 'filename', None)

    file_content = getattr(uploaded_file, 'file', None)
    real_path = ''

    if file_name and file_content:
        content_t = mimetypes.guess_type(file_name)[0]
        real_path = os.path.join('/', bucket_name, user.user_id(), file_name)

        with cloudstorage.open(real_path, 'w', content_type=content_t) as f:
            f.write(file_content.read())

此代码在我部署时运行良好,但在本地计算机上运行不佳。我收到以下错误消息。

ValueError: Path should have format /bucket/filename but got /app_default_bucket\185804764220139124118\test.pdf

最佳答案

您正在使用os.path.join()来操作本地路径以外的其他内容。

试试这个:

    real_path = '/' + bucket_name + '/' + user.user_id()+ '/' +file_name

或者您可以使用posixpath:

import posixpath
posixpath.join('/', bucket_name, user.user_id(), file_name)

引用:https://docs.python.org/2/library/os.path.html#module-os.path - “os.path 模块...可用于本地路径。”

关于python - 无法使用 Google 云存储将文件保存到存储桶。可以在服务器上运行,但不能在本地运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141384/

相关文章:

python - Django - 无法让模型在模板中显示

python - 在正则表达式中使用 unicode char 代码

python - Pandas 创建新列,其中另一列中的所有条目对应于唯一值

google-app-engine - 将托管在谷歌应用引擎中的应用程序列入白名单

google-api - Google Storage API 禁止 ipRefererBlocked 错误

python - 按名称顺序迭代文件,Python

node.js - Google Cloud Datastore 是否支持像 Mongodb $set 这样的部分更新?

html - 我想将上传的图片显示到html图片标签中

google-app-engine - NoClassDefFoundError : Could not initialize OauthRawGcsServiceFactory on production environment

java - 使用 Java 且没有第 3 方框架(iOS 客户端)的谷歌应用引擎自定义身份验证 - 设计合理吗?