简体   繁体   English

使用 Python 在 GCS 中解压缩文件 - 如何添加项目和身份验证

[英]Uncompress file in GCS with Python - How to add project and auth

In this code在这段代码中

from google.cloud import storage
from zipfile import ZipFile
from zipfile import is_zipfile
import io

def zipextract(bucketname, zipfilename_with_path):

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucketname)

    destination_blob_pathname = zipfilename_with_path
    
    blob = bucket.blob(destination_blob_pathname)
    zipbytes = io.BytesIO(blob.download_as_string())

    if is_zipfile(zipbytes):
        with ZipFile(zipbytes, 'r') as myzip:
            for contentfilename in myzip.namelist():
                contentfile = myzip.read(contentfilename)
                blob = bucket.blob(zipfilename_with_path + "/" + contentfilename)
                blob.upload_from_string(contentfile)

zipextract("mybucket", "path/file.zip") # if the file is gs://mybucket/path/file.zip

how to add the project and auth - @sylvain-gantois implied it can be done.如何添加项目和身份验证 - @sylvain-gantois 暗示它可以完成。 Any help would be awesome.任何帮助都是极好的。

All - I worked it out全部 - 我解决了

data = {CONTENTS OF GOOGLE IAM JSON}

with open('google.json', 'w') as outfile:
    json.dump(data, outfile, ensure_ascii=False)

google_credentials = service_account.Credentials.from_service_account_file('google.json')
storage_client = storage.Client(project='PROJECTID', credentials=google_credentials)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM