PythonでGoogle Cloud Storageを操作

PythonでGoogle Cloud Storageを操作

GCSバケット作成→サービスアカウント作成→PythonでGCS操作

Google Cloud Storage(GCS)はGoogle Cloud Platform(GCP)の提供するストレージサービス。
AWSでいうところのS3。

Pythonでファイル操作できると便利なので実験。

1. テスト用のバケット作成

バケットを作成して実験用のファイルを置く。
GCPのアカウント・プロジェクトは作成済。

1.1. バケット作成

GCSにアクセス。

https://console.cloud.google.com/storage



「バケットを作成」



適当な名前、ここでは「bucket-20220910」と付けて「作成」。
GCSにバケット「bucket-20220910」が生成される。

1.2. ファイルアップロード

事前に適当なcsvファイルを用意しておく。



さっき作ったバケット「bucket-20220910」を選択。
「ファイルをアップロード」として適当なファイル「sample.csv」をアップロード。



こんな感じになる。

2. サービスアカウント準備

GCPに外部からアクセスするためにサービスアカウントが必要となる。

2.1. ロール作成

サービスアカウントに付与するためのロールを作成する。



「IAMと管理」→「ロール」→「ロールを作成」。



適当な名前「sample-role」を付けて「権限を追加」。



権限が星の数ほどあり選ぶのが大変なのでフィルタに検索ワードを入れる。
目的の権限にチェックを付けて追加する。
今回必要な権限は以下の4つ。



「storage.buckets.list」、「storage.objects.list」、「storage.buckets.get」、「storage.objects.get」を選択して「追加」。

ここで作成したロールを次にサービスアカウントへ付与する。

2.2. サービスアカウント作成

GCSにアクセス。



「IAMと管理」→「サービスアカウント」。



「サービスアカウントを作成」



「サービスアカウントID」に適当な名前「sample」を付けて「作成して実行」。



「ロールを選択」して「続行」。



選択するのはさっき作った「sample-role」。



特に何もせず[「完了」。

サービスアカウントが作られた。

2.3. サービスアカウントのキー作成

サービスアカウントを使用するためのキーを作成する。



さっき作ったサービスアカウントを選択。
「キー」→「鍵の追加」→「新しい鍵を作成」。



「JSON」を選択して「作成」。

作成されたキーであるjsonファイルがダウンロードされる。
このキーを後で使う。

3. Python

2.3.で作成したjsonファイル(サービスアカウントキー)を準備しておく。
コード内から参照する。

3.1. 環境設定

Anacondaが既にインストールされている前提。
入ってなければ以下を参考にして入れる。
別にAnacondaである必要はない。

以下のように「gcp」という名前の環境を作り、必要なライブラリをインストール。

1
2
3
4
conda create -n gcp
activate gcp
conda install -c conda-forge google-cloud-storage
conda install pandas

pipでもなんでもいい。

3.2. バケットリスト取得

GCS内のバケットを取得して名前を出力。

1
2
3
4
5
6
7
from google.cloud import storage
from google.oauth2.service_account import Credentials

credentials = Credentials.from_service_account_file(filename="サービスアカウントキー.json")
storage_client = storage.Client(credentials=credentials)
buckets = list(storage_client.list_buckets())
print(buckets)

3.3. バケット内のファイルリスト取得

指定したバケット内のファイルを取得して名前を出力。

1
2
3
4
5
6
7
8
9
from google.cloud import storage
from google.oauth2.service_account import Credentials

credentials = Credentials.from_service_account_file(filename="サービスアカウントキー.json")
storage_client = storage.Client(credentials=credentials)
bucket = storage_client.get_bucket("バケット名(bucket-20220910)")
blobs = bucket.list_blobs()
for blob in blobs:
print(blob.name)

3.4. バケット内のcsvファイル読み込み

指定したcsvファイルを取得。
pandasによって読み込み。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from google.cloud import storage
from google.oauth2.service_account import Credentials
import pandas as pd
import io

credentials = Credentials.from_service_account_file(filename="サービスアカウントキー.json")
storage_client = storage.Client(credentials=credentials)

bucket_name = "バケット名(bucket-20220910)"
file_name = "ファイルパス(sample.csv)"
bucket = storage_client.get_bucket(bucket_name)
blob = storage.Blob(file_name, bucket)
content = blob.download_as_string()
df = pd.read_csv(io.BytesIO(content))
print(df)

4. エラー

〇〇に対応する権限がサービスアカウントに付与されたロールに与えられていないと以下のエラーが発生する。

1
403 POST ~~ ××.iam.gserviceaccount.com does not have 〇〇 access to the Google Cloud project.

5. 参考

サービスアカウント
https://cloud.google.com/iam/docs/grant-role-console?hl=ja

google-cloud-storage(ライブラリ)
https://googleapis.dev/python/storage/latest/client.html

タグ , ,

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×