在本地开发中,如果不想使用Google服务账号密钥,可以考虑使用Google Cloud SDK提供的用户授权凭据来进行开发。以下是一个解决方法的示例代码:
import os
from google.cloud import storage
# 设置用户授权凭据路径
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/path/to/your/credentials.json'
def download_file(bucket_name, source_blob_name, destination_file_name):
"""下载Google Cloud Storage中的文件"""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(f'文件 {source_blob_name} 已下载到 {destination_file_name}')
def upload_file(bucket_name, source_file_name, destination_blob_name):
"""上传文件到Google Cloud Storage"""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print(f'文件 {source_file_name} 已上传到 {destination_blob_name}')
# 示例用法
bucket_name = 'your-bucket-name'
source_blob_name = 'path/to/source/blob.txt'
destination_file_name = 'path/to/destination/file.txt'
# 下载文件
download_file(bucket_name, source_blob_name, destination_file_name)
# 上传文件
source_file_name = 'path/to/source/file.txt'
destination_blob_name = 'path/to/destination/blob.txt'
upload_file(bucket_name, source_file_name, destination_blob_name)
在上述代码中,我们通过设置GOOGLE_APPLICATION_CREDENTIALS
环境变量来指定用户授权凭据的路径。然后使用google.cloud.storage
模块提供的API来进行文件的下载和上传操作。请确保你已经安装并配置了Google Cloud SDK,并将示例中的路径替换为你自己的凭据路径、存储桶名称、文件路径等信息。