🦁

python CloudStorage

1 min read

前提

  • IAMからサービスアカウントで権限つけてダウンロード
  • 適当な文字列のファイル hello.txt を用意

ファイル構成

.
├── Dockerfile
├── app.py
├── credentials.json
└── hello.txt

コード

FROM python:3.9-slim

ENV APP_HOME /app
WORKDIR $APP_HOME
COPY . ./

RUN apt-get update
RUN apt-get install tree
RUN pip install google-auth google-cloud-storage
from google.cloud import storage
from google.oauth2 import service_account

def upload_to_storage():
    credentials = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    client = storage.Client(credentials=credentials, project=credentials.project_id,)
    bucket = client.get_bucket('myk_test')
    blob = bucket.blob('hello_gcs.txt')
    blob.upload_from_filename('hello.txt')


def download_from_storage():
    credentials = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    client = storage.Client(credentials=credentials, project=credentials.project_id,)
    bucket = client.get_bucket('myk_test')
    blob = bucket.blob('hello_gcs.txt')
    blob.download_to_filename('hello2.txt')

def create_bucket():
    credentials = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )
    client = storage.Client(credentials=credentials, project=credentials.project_id,)
    client.create_bucket('myk_test')

Discussion

ログインするとコメントできます