LoginSignup
0
0

More than 1 year has passed since last update.

GCSにファイルをアップロードする

Posted at

事前準備

  1. Cloud StorageにBucketを作成する
  2. Cloud Storageへの書き込み権限を持つサービスアカウントを作成する
  3. 作成したサービスアカウントのクレデンシャルファイル(JSON)をローカルに保存する

構成

main.pyは実行コード、sample.jsonはアップロードしたいファイル、<your-credential-file>.jsonは認証に必要なファイル(事前準備3で取得したファイル)です。

$ tree
.
├── main.py
├── sample.json
└── <your-credential-file>.json

コード

事前に、pipを使用して必要なライブラリをインストールします。

$ pip install --upgrade google-cloud-storage

以下のコードがサンプルです。

main.py
from google.cloud import storage
import json

credential_file = './<your-credential-file>.json'

client = storage.Client.from_service_account_json(json_credentials_path=credential_file)

# 作成したバケットの名前を指定します
bucket = storage.Bucket(client, '<your-bucket-name>')

blob = bucket.blob('uploaded_sample.json')
blob.upload_from_filename('sample.json')

これで、python main.pyを実行すると、作成したバケットにファイルがアップロードされます。

環境変数を使用する場合

通常、クレデンシャルなどのファイルを直接リポジトリに保持するのは避けられるので、事前準備で取得したJSONファイルの内容を環境変数として読み込む方法です。

事前に環境変数にJSONの値を登録します。

$ export GOOGLE_APPLICATIOON_CREDENTIALS_JSON='<JSONの中身>'

先ほどのコードを以下のように修正します。

main.py
from google.cloud import storage
import os
import json

- credential_file = './sandbox01-281123-99edfe2e0eb7.json'
+ json_str = os.environ['GOOGLE_APPLICATION_CREDENTIALS_JSON']
+ credentials = json.loads(json_str)

- client = storage.Client.from_service_account_json(json_credentials_path=credential_file)
+ client = storage.Client.from_service_account_info(credentials)

bucket = storage.Bucket(client, 'monitoring-ai-bucket')

blob = bucket.blob('uploaded_sample2.json')
blob.upload_from_filename('sample.json')

以上です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0