python - 使用 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'`
有人可以告诉我我做错了什么。
解决方案
实际上,您的代码将无法正常工作,因为您没有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)
推荐阅读
- javascript - 以下代码是否同步返回已解决的承诺?
- powerbi - DAX:仅当数据集中所有年份的数据都存在时才计算
- r - 如何修复地图上不正确的自动标签(tmap)
- python - 如何将robotframework-hub生成的libdoc保存到本地
- spring - 如何连接两个 docker 容器
- javascript - 地图内的JS地图
- python - sqlalchemy,连接到不同端口上的 sqlexpress 实例
- python - QWebEngineView中央小部件时如何在QWebEngineView之上制作QFrame
- flutter - Flutter - 在BottomNavigationBar的中间图标添加弹出菜单按钮
- java - 设置值回到开始