首页 > 解决方案 > 使用 python 为 Cloud Storage 中的对象生成签名 URL

问题描述

我正在尝试使用 python 为云存储中的对象生成签名 URL。

import datetime as dt
ini_time_for_now = dt.datetime.now() 
expiration_time = ini_time_for_now + dt.timedelta(minutes = 15) 
print(expiration_time)

client = storage.Client()
bucket = client.get_bucket(bucketname)
blob = bucket.blob(pdffolder) 
blob.upload_from_filename(pdffilename)

url = blob.generate_signed_url('cred.json', bucketname,pdffolder,expiration=expiration_time)

我收到此错误。

Traceback (most recent call last):
File "entryscript.py", line 18, in <module>
main()
File "entryscript.py", line 13, in main
testpdf(sys.argv[0], sys.argv[1])

File "/home/xxxx/GitHub/patch_python/local_test_scripts/patchQuick/Instant_analysis/test.py", line 504, in testpdf

url = blob.generate_signed_url('cred.json', bucketname, 
pdffolder,expiration=expiration_time) 
TypeError: generate_signed_url() got multiple values for argument 'expiration'`

有人可以告诉我我做错了什么。

标签: pythongoogle-cloud-storage

解决方案


实际上,您的代码将无法正常工作,因为您没有generate_signed_url()根据其文档正确使用该方法。此外,我认为您将generate_signed_url对象的方法与此处blob显示的示例方法混淆了:

def generate_signed_url(service_account_file, bucket_name, object_name,
                       subresource=None, expiration=604800, http_method='GET',
                       query_parameters=None, headers=None):

您应该考虑的另一件事是到期日期应该是UTC

以下代码Signed URL从已创建的对象创建一个,但您可以修改它以满足您的要求:

from google.oauth2 import service_account
from google.cloud import storage
from datetime import datetime, timezone, timedelta

#Define the service account key and project id
KEY='path/to/key.json'
PROJECT='PROJECT_ID'

#create a credential to initialize the Storage client
credentials = service_account.Credentials.from_service_account_file(KEY)
client = storage.Client(PROJECT,credentials)

#Define your Storage bucket and blob
bucketname = "BUCKET_NAME"
file = "BLOB_NAME"

#Get the time in UTC
ini_time_for_now = datetime.now(timezone.utc)

#Set the expiration time
expiration_time = ini_time_for_now + timedelta(minutes = 1) 

#Initialize the bucket and blob
bucket = client.get_bucket(bucketname)
blob = bucket.get_blob(file)

#Get the signed URL
url = blob.generate_signed_url(expiration=expiration_time)

#Print the URL
print (url)

推荐阅读