Forked from jezhumble/python_cloud_function_get_signed_url.py
Created
January 25, 2020 17:03
-
-
Save jbn/8d3c7cedf0300c5be23c76f0ccbc3ae6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright 2019 Google LLC. | |
# SPDX-License-Identifier: Apache-2.0 | |
# This snippet shows you how to use Blob.generate_signed_url() from within compute engine / cloud functions | |
# as described here: https://cloud.google.com/functions/docs/writing/http#uploading_files_via_cloud_storage | |
# (without needing access to a private key) | |
# Note: as described in that page, you need to run your function with a service account | |
# with the permission roles/iam.serviceAccountTokenCreator | |
import os, google.auth | |
from google.auth.transport import requests | |
from google.auth import compute_engine | |
from datetime import datetime, timedelta | |
from google.cloud import storage | |
auth_request = requests.Request() | |
credentials, project = google.auth.default() | |
storage_client = storage.Client(project, credentials) | |
data_bucket = storage_client.lookup_bucket(os.getenv("BUCKET_NAME")) | |
signed_blob_path = data_bucket.blob("FILENAME") | |
expires_at_ms = datetime.now() + timedelta(minutes=30) | |
# This next line is the trick! | |
signing_credentials = compute_engine.IDTokenCredentials(auth_request, "", service_account_email=credentials.service_account_email) | |
signed_url = signed_blob_path.generate_signed_url(expires_at_ms, credentials=signing_credentials, version="v4") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment