当前位置: 首页 > 知识库问答 >
问题:

如何用凭据初始化Google云存储

龙玺
2023-03-14
from google.cloud import storage
self.client = storage.Client.from_service_account_json('/Users/david/file-163219.json')
credentials_dict = {
      "type": "service_account",
      "project_id": "asdf-163219",
      "private_key_id": "asdf2938492837498234",
}
credentials = service_account.Credentials.from_service_account_info(credentials_dict)
self.client = storage.Client(credentials=credentials)

通过证书口述的正确方法是什么?

共有1个答案

杨豪
2023-03-14
#!/usr/bin/env python
from google.cloud import storage
from google.oauth2 import service_account
import json
import os
import tempfile
if __name__ == '__main__':
    jsonfile = u"""<HERE GOES THE CONTENT OF YOUR KEY JSON FILE.
    CONSIDER THAT THERE ARE BACKSLASHES WITHIN THE PRIVATE KEY
    THEREFORE USE AN EXTRA BACKSLASH. FOR INSTANCE: 
    -----BEGIN PRIVATE KEY-----\\nSomeRandomText
    INSTEAD OF: 
    -----BEGIN PRIVATE KEY-----\nSomeRandomText"""
    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'w') as tmp:
            tmp.write(jsonfile)
        credentials = service_account.Credentials.from_service_account_file(path)
        storage_client = storage.Client(credentials=credentials)
        bucket = storage_client.get_bucket("your-bucket")
        blobs = bucket.list_blobs()
        for blob in blobs:
            print(blob.name)
    finally:
        os.remove(path)
 类似资料: