使用python为云存储中的对象生成签名URL

2024-09-27 18:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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'`

有人能告诉我我做错了什么吗


Tags: pyurlforbuckettimelinedtblob
3条回答

希望这能帮助别人

  1. 浏览API和服务的->;证书->;创建凭据->;服务帐户->;提供适当的服务帐户名,并将云存储管理员指定为角色。下载密钥(.json文件)

  2. 浏览到云存储Bucket,确保在该Bucket的permissions选项卡中存在上面创建的服务帐户。如果没有,请单击添加成员,添加上面创建的服务帐户并分配云存储管理员角色

  3. 使用上面@fervelet给出的代码并获取签名的URL

我遇到了完全相同的错误-出于某种原因,我返回测试的URL将&HTML编码为&amp;,这导致了此错误

对你来说可能不是同一个问题,只是以防万一

实际上,您的代码不会工作,因为您没有根据documentation正确使用generate_signed_url()方法。此外,我认为您将blob对象的方法^{}与所示的示例方法here混淆了:

def generate_signed_url(service_account_file, bucket_name, object_name,
                       subresource=None, expiration=604800, http_method='GET',
                       query_parameters=None, headers=None):
<> P>另一件事你应该考虑的是到期日期应该在<强> UTC/<强>p>

以下代码从已创建的对象创建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)

相关问题 更多 >

    热门问题