AppEngineで動かすアプリを作っていて、Blobstoreを使おうかなーと思って久しぶりにドキュメントを見たら、CloudStorageを使うことが推奨されていたので、試してた。
https://developers.google.com/appengine/docs/python/googlecloudstorageclient/?hl=ja
1〜2年前だかはgoogle.appengine.api.filesあたりでCloudStorageのAPIを使うことができていたけど、これは今だと非推奨らしい。 代わりにクライアントライブラリを使用しろとのこと。クライアントライブラリはPyPIからダウンロードできる。
GoogleAppEngineCloudStorageClient 1.9.22.1 : Python Package Index
使い方はGetting Startedの通りで問題なく動作。
App Engine and Google Cloud Storage Sample | Python | Google Cloud Platform
手元ではこんな感じで使ってる。
# coding: utf-8 import os import cloudstorage as gcs from google.appengine.api import app_identity # GCSタイムアウト設定 retry_params = gcs.RetryParams( initial_delay=0.2, max_delay=5.0, backoff_factor=2, max_retry_period=15) gcs.set_default_retry_params(retry_params) def get_bucket_name(): """バケット名を返す """ return os.environ.get( 'BUCKET_NAME', app_identity.get_default_gcs_bucket_name()) def write_file(filename, content, content_type): """GCSにファイル保存 """ bucket_name = get_bucket_name() filepath = '/' + bucket_name + '/' + filename with gcs.open(filepath, 'w', content_type=content_type) as gcs_file: gcs_file.write(content) def read_file(filename): """GCSからファイルを読み込み """ bucket_name = get_bucket_name() filepath = '/' + bucket_name + '/' + filename with gcs.open(filepath) as gcs_file: return gcs_file.read()
動かす前にプロジェクト用のバケットを作成しておく必要がある。デフォルトバケットの場合は、AppEngineの管理コンソールの「Application Settings」->「Cloud Integration」から作成できる。
保存したファイルはDeveloper Consoleの画面からも管理できる。
また、GoogleAppEngineから使う場合、デフォルトバケットだと5GBまで無料で使えるそう。
Default GCS Bucket
ローカル環境ではスタブで動作してくれるし、いい感じ。