python - 如何从 Google Cloud Platform 存储下载文件

标签 python google-cloud-platform google-cloud-storage

我正在阅读谷歌云存储的 python 文档,并成功地创建了一个上传文件的方法,但是,我无法找到使用 blob 的 URL 下载文件的方法。我可以使用文件名下载文件,但这不切实际,因为用户可以上传同名文件。该 blob 是私有(private)的。我可以访问 blob 的 URL,所以我想知道是否有办法使用此链接下载文件。
这是我完美的上传代码:

def upload_blob(bucket_name, filename, file_obj):
    if filename and file_obj:
        storage_client = storage.Client()
        bucket = storage_client.bucket('example-storage-bucket')
        blob = bucket.blob(filename)
        blob.upload_from_file(file_obj) # binary file data
        form_logger.info('File {} uploaded'.format(filename))
        return blob
此代码下载文件,但我只能用 blob 名称而不是 URL 来计算它:
def download_blob(bucket_name, url):
    if url:
        storage_client = storage.Client()
        bucket = storage_client.bucket('example-storage-bucket')
        blob = bucket.blob(url)
        blob.download_to_filename("example.pdf")
关于如何使用 blob 的媒体链接 URL 下载文件的任何建议或想法?

最佳答案

例如,存储桶 example-storage-bucket有文件folder/example.pdf及其
链接地址 https://storage.cloud.google.com/example-storage-bucket/folder/example.pdf
网址 gs://example-storage-bucket/folder/example.pdf使用以下函数使用 GCS 链接 URL 下载 blob(如果您使用的是 Python 3.x):

import os
from urllib.parse import urlparse

def decode_gcs_url(url):
    p = urlparse(url)
    path = p.path[1:].split('/', 1)
    bucket, file_path = path[0], path[1] 
    return bucket, file_path

def download_blob(url):
    if url:
        storage_client = storage.Client()
        bucket, file_path = decode_gcs_url(url)
        bucket = storage_client.bucket(bucket)
        blob = bucket.blob(file_path)
        blob.download_to_filename(os.path.basename(file_path))

关于python - 如何从 Google Cloud Platform 存储下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62745795/

相关文章:

python - 运行字符串中包含的 Python 代码

mysql - 如何在Visual Studio中访问Google云平台中的mysql数据库

google-cloud-platform - Google Cloud - 通过私钥访问Linux VM

google-cloud-storage - 使用 gsutil move 多个文件

python - 选择 django 表单数据中的选项?

python - python + selenium + chromedriver 如何使用鼠标滚轮?

python - Caffe:如何加载图像数据进行语义分割

mysql - 如何在 GCP 上运行 Ghost with MySQL?

google-app-engine - 从 Google BigQuery 提取结果到云存储 golang

javascript - GCS 中的 Google Cloud Storage Bucket : XML error when reloading an Ember. js 应用