如何在Google Cloud Function中生成链接到特定存储段GCS的预签名URL?

问题描述

如何将使用服务帐户生成的私钥文件添加到云功能以进行身份​​验证?

以下代码返回auth凭据错误,它说我需要一个私钥来对凭据进行签名。如何创建它并传递云功能

import datetime

from google.cloud import storage


def generate_download_signed_url_v4(bucket_name,blob_name):
    """Generates a v4 signed URL for downloading a blob.

    Note that this method requires a service account key file. You can not use
    this if you are using Application Default Credentials from Google Compute
    Engine or from the Google Cloud SDK.
    """
    # bucket_name = 'your-bucket-name'
    # blob_name = 'your-object-name'

    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(minutes=15),# 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("curl '{}'".format(url))
    return url

解决方法

我可以帮助您找到有关如何使用Python在GCF中创建签名网址的信息。您需要使用Cloud Storage Python Client libraries,如官方GCP文档中的example所述。此外,Medium上的example也可以为您提供帮助。