设置GCP环境变量以访问存储桶

时间:2019-09-10 20:44:43

标签: python google-cloud-platform bucket

我正在使用GCP存储桶来存储数据,我向存储桶读取文件或从存储桶读取写入文件的第一种方法是:

def upload_blob(bucket_name, source_file_name, destination_blob_name,credentials):
    """Uploads a file to the bucket."""
    client = storage.Client.from_service_account_json(credentials)
    bucket = client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_filename(source_file_name) 

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))


def download_blob(bucket_name, source_blob_name, destination_file_name,credentials):
    """Downloads a blob from the bucket."""
    storage_client = storage.Client.from_service_account_json(credentials)
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(source_blob_name)

    blob.download_to_filename(destination_file_name)

    print('Blob {} downloaded to {}.'.format(
        source_blob_name,
        destination_file_name))

这确实可以正常工作,但是我想将其保存为环境变量,以使文件不会一直保留。据我了解,如果没有提供凭据,Google会更改:

client = storage.Client.from_service_account_json(credentials)

针对:

client = storage.Client()

然后在google中搜索默认凭据,可以通过执行以下操作来设置该凭据:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

我在做什么,没有得到任何错误:

enter image description here

但是当我尝试访问存储桶时,出现以下错误:

DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

我正在跟踪链接,创建一个新密钥:

enter image description here

尝试改用那个,但是仍然遇到相同的错误。

0 个答案:

没有答案