How to download a file from Google Cloud Platform storage(如何从 Google Cloud Platform 存储下载文件)
问题描述
我正在阅读谷歌云存储的 python 文档,并成功地创建了一个上传文件的方法,但是,我无法找到使用 blob 的 URL 下载文件的方法.我能够使用文件名下载文件,但这不切实际,因为用户可以上传同名文件.该 blob 是私有的.我可以访问 blob 的 URL,所以我想知道是否可以使用此链接下载文件.
I was reading the python documentation for google cloud storage and was successfully able to create a method that uploads files, however, I am not able to find a way to download files using a blob's URL. I was able to download the file using the filename, but that's not practical since the user could upload files with the same name. The blob is private. I have access to the blob's URL, so I was wondering if there is a way to download files using this link.
这是我完美运行的上传代码:
This is my upload code which works perfectly:
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 来判断:
This code downloads the file, but I could only figure it out with the blob name, not 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 下载文件有任何建议或想法吗?
Any suggestions or thoughts on how to download the file using the blob's media link URL?
推荐答案
比如bucket example-storage-bucket
有文件folder/example.pdf
及其
For example, bucket example-storage-bucket
has file folder/example.pdf
and its
链接 URL 是 https://storage.cloud.google.com/example-storage-bucket/folder/example.pdf
和URI 是 gs://example-storage-bucket/folder/example.pdf
使用以下函数通过 GCS 链接 URL 下载 blob(如果您使用的是 Python 3.x):
Use below function to download blob using GCS link URL(if you are using 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))
这篇关于如何从 Google Cloud Platform 存储下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从 Google Cloud Platform 存储下载文件
基础教程推荐
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01