Google 签名网址过期问题

问题描述 投票:0回答:1

我面临谷歌签名网址到期时间的问题。我希望签名的 URL 在 5 秒后过期,但它并没有过期。这是我的Python代码:

from datetime import datetime,timezone

                expiration_time = datetime.now(timezone.utc) + timedelta(seconds=5)
                

                bucket = client.get_bucket(settings.GS_BUCKET_NAME)
                blob = bucket.blob(object_name)
                signed_url = blob.generate_signed_url(expiration=expiration_time)

即使我尝试使用此代码也遇到同样的问题

storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(blob_name)

    url = blob.generate_signed_url(
        version="v4",
        # This URL is valid for 15 minutes
        expiration=datetime.timedelta(seconds=5),
        # Allow GET requests using this URL.
        method="GET",
    )

    print("Generated GET signed URL:")
    print(url)
    print("You can use this URL with any user agent, for example:")
    print(f"curl '{url}'")
    return url

提前致谢

google-cloud-platform url bucket signed
1个回答
0
投票

~代码对我有用。

python3 -m venv venv
source venv/bin/activate
python3 -m pip install google-cloud-storage
export PROJECT="..."
export BUCKET="..."
export BLOB="..."

ACCOUNT="tester"
EMAIL=${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com

gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}

gcloud iam service-accounts keys create ${PWD}/${ACCOUNT}.json \
--iam-account=${EMAIL} \
--project=${PROJECT}

# Too broad, but ...
gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${EMAIL} \
--role=roles/storage.admin

export GOOGLE_APPLICATION_CREDENTIALS=${PWD}/${ACCOUNT}.json

python3 main.py

main.py

import logging
import os
import requests
import time

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


logging.basicConfig(format='%(asctime)s: %(message)s', level=logging.INFO)

project = os.getenv("PROJECT")
bucket_name = os.getenv("BUCKET")
blob_name = os.getenv("BLOB")


duration: float = 5

storage_client = storage.Client(project=project)
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(blob_name)

url = blob.generate_signed_url(
    version="v4",
    expiration=datetime.now(timezone.utc) + timedelta(seconds=duration),
    method="GET",
)
logging.info("Received URL")

logging.info("Calling")
logging.info(f"Received: {requests.get(url).status_code}")

logging.info(f"Sleeping: {duration}")
time.sleep(duration)

logging.info("Calling")
logging.info(f"Received: {requests.get(url).status_code}")

产量:

2024-08-16 10:25:04,374: Received URL
2024-08-16 10:25:04,374: Calling
2024-08-16 10:25:04,503: Received: 200
2024-08-16 10:25:04,504: Sleeping: 5
2024-08-16 10:25:09,504: Calling
2024-08-16 10:25:09,590: Received: 400
© www.soinside.com 2019 - 2024. All rights reserved.