gpt4 book ai didi

python - 使用 python 为 Cloud Storage 中的对象生成签名 URL

转载 作者:行者123 更新时间:2023-12-02 02:47:57 26 4
gpt4 key购买 nike

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

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

最佳答案

实际上,您的代码将无法工作,因为您没有根据其 documentation 正确使用 generate_signed_url() 方法。 。另外我认为你混淆了方法 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):

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

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

关于python - 使用 python 为 Cloud Storage 中的对象生成签名 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62487672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com