Python関数からGoogleCloud Storageにログインする方法は?
私はグーグルクラウドストレージに不慣れで、1日1回blobをダウンロードする機能を設定しようとしています。現在、Jupyter Notebookで作業していますが、最終的に、コードはAzureFunctionで実行されます。バケットに接続するクライアントの設定に苦労しています。私はグーグルに接続することを可能にするサービスアカウント資格情報JSONを持っています。
ローカルで私は解決策を見つけました:
from google.cloud import storage
client = storage.Client.from_service_account_json('<PATH_TO_SERVICE_ACCOUNT_JSON>')
問題は、JSONをクラウドに保存するパスがないのに、キーボールトに保存することです。私は次の解決策を思いついた:
from google.cloud import storage
import json
from google.oauth2 import service_account
string_key = get_key_from_key_vault()
service_account_info = json.loads(string_key)
google_credentials = service_account.Credentials.from_service_account_info(
service_account_info
)
scoped_credentials = google_credentials.with_scopes(
['https://www.googleapis.com/auth/cloud-platform.read-only'])
print(type(scoped_credentials))
client = storage.Client(credentials = scoped_credentials)
scoped_credentials = ...
パーツが必要かどうかは完全にはわかりませんが、バケットに対する読み取り権限しかありません。(その部分をスキップしてもエラーは同じままです)
この解決策を選択すると、次のエラーが発生します。
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
私はすでに資格情報を明示的に設定していると思うので、私が間違っていることの手がかりがありません。
ベストP
回答
GOOGLE_APPLICATION_CREDENTIALSjsonファイルのパスを使用して環境変数を設定し、パラメーターなしでストレージクライアントを起動して関数を認証できます。
client = storage.Client()
*デフォルトでは、ストレージクライアントは環境変数のファイルパスを使用しますGOOGLE_APPLICATION_CREDENTIALS
これはJSON認証情報を使用する最も簡単な方法であり、ほとんどのGoogle CloudPythonライブラリと互換性があります。
さらにいくつかのテストを行った後、追加し忘れたことがわかりましたproject = None
。追加する場合は、次のコマンドを使用して、機能するクライアントを作成します。
client = storage.Client(project = None, credentials = scoped_credentials)
あなたの助けと思考のための食べ物をありがとう:-)
(コメントのコードフォーマットがひどいので、私は答えの部分を使用します)
これを試して、2アクセストークンが印刷されているかどうか教えていただけますか?
from google.cloud import storage
import json
from google.oauth2 import service_account
from google.auth.transport import requests as grequests
string_key = get_key_from_key_vault()
service_account_info = json.loads(string_key)
google_credentials = service_account.Credentials.from_service_account_info(
service_account_info
)
google_credentials.refresh(grequests.Request())
print(google_credentials.token)
scoped_credentials = google_credentials.with_scopes(
['https://www.googleapis.com/auth/cloud-platform.read-only'])
scoped_credentials.refresh(grequests.Request())
print(scoped_credentials.token)