无法使用谷歌云存储将文件保存到存储桶.可在服务器上工作,但不能在本地工作



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

    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_bucket185804764220139124118test.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 module…可用于本地路径。"

最新更新