Shr*_*rey 6 python google-cloud-storage google-cloud-platform
我正在阅读 Google 云存储的 python 文档,并成功创建了上传文件的方法,但是,我无法找到使用 blob 的 URL 下载文件的方法。我能够使用文件名下载文件,但这并不实用,因为用户可以上传具有相同名称的文件。该 blob 是私有的。我可以访问该 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
Run Code Online (Sandbox Code Playgroud)
此代码下载文件,但我只能通过 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")
Run Code Online (Sandbox Code Playgroud)
关于如何使用 blob 的媒体链接 URL 下载文件有什么建议或想法吗?
例如,存储桶example-storage-bucket
有文件folder/example.pdf
及其
链接 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):
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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8526 次 |
最近记录: |