🔥
Firebase StorageをPythonで操作
背景
Firestoreを使っていたが、大量のデータアクセスを一週間に1回位やる場合ならStorageで問題ない事に気がついて調べました。
結論
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
#from firebase_admin import storage
from google.cloud import storage
GOOGLE_APPLICATION_CREDENTIALS=os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
FIREBASE_STORAGE_BUCKET=os.environ["FIREBASE_STORAGE_BUCKET"]
cred = credentials.Certificate(GOOGLE_APPLICATION_CREDENTIALS)
firebase_admin.initialize_app(cred,{'storageBucket':FIREBASE_STORAGE_BUCKET})
bucket = storage.bucket()
def upload_blob(source_file_name, destination_blob_name):
storage_client = storage.Client()
bucket = storage_client.bucket(FIREBASE_STORAGE_BUCKET)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print(
"File {} uploaded to {}.".format(
source_file_name, destination_blob_name
)
)
def download_blob(source_blob_name, destination_file_name):
storage_client = storage.Client()
bucket = storage_client.bucket(FIREBASE_STORAGE_BUCKET)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(
"Blob {} downloaded to {}.".format(
source_blob_name, destination_file_name
)
)
def blob_list(prefix=""):
storage_client = storage.Client()
bucket = storage_client.bucket(FIREBASE_STORAGE_BUCKET)
blobs = list(bucket.list_blobs(prefix=prefix))
print(
"Blob list to {}.".format(
blobs
)
)
return blobs
blob_listでprefixを指定すれば特定フォルダ配下のファイルのみを抽出することもできます。
下記を参考にしています。
参考:https://googleapis.dev/python/storage/latest/client.html
使い方
環境変数でFIREBASE_STORAGE_BUCKETにはバケット名、GOOGLE_APPLICATION_CREDENTIALSにはFirebaseからダウンロードした認証ファイルを設置してください。
バケット名
Firebase storageの上部に書いてある文字列です。
この場合はgs://を抜いたVideo-xxxx.appspot.comという部分になります。
Keyファイル
1.プロジェクトの概要横からプロジェクトを設定を選択してください。
2. 上のタブからサービスアカウントを選択
3. 下にある新しい秘密鍵の生成を押すとJSONファイルをダウンロードできます。
Discussion