0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

VS Codeの設定

もしもCloudRunが初めてで、VSCodeを使っているのなら、このあたりを試してみてデプロイ出来るようにしておくと良いです。

サンプル アプリケーションからの Cloud Run サービスの作成 | Cloud Code for VS Code | Google Cloud

ソース

CloudRunように作っています。CloudFunctionsでも手直せば動くと思う。
言語はPythonです。

import os
from functions.upload_file import upload_gcs
from flask import Flask, request

# pylint: disable=C0103
app = Flask(__name__)

@app.route('/upload-gcs', methods=['GET', 'POST'])
def local_upload_gcs():
    return upload_gcs(request)

if __name__ == '__main__':
    server_port = os.environ.get('PORT', '8080')
    app.run(debug=False, port=server_port, host='0.0.0.0')

肝心のアップロード処理はこんな感じで

import json
from apiclient import discovery
from googleapiclient.http import MediaIoBaseUpload
from oauth2client.client import GoogleCredentials

def upload_gcs(request):
    if request.args and 'image' in request.args:
        image = request.args.get('image')
    else:
        image = request.files.get('image')
    if request.args and 'bucketname' in request.args:
        request_bucketname = str(request.args.get('bucketname'))
    elif request.form and 'bucketname' in  request.form:
        request_bucketname = str(request.form.get('bucketname'))

    # Retrieve credentials
    credentials = GoogleCredentials.get_application_default()
    # Create service object
    service = discovery.build('storage', 'v1', credentials=credentials)
    # Create media object
    media = MediaIoBaseUpload(
        image,
        mimetype=image.mimetype
    )
    # Create request
    request = service.objects().insert(
        bucket=request_bucketname,
        name=image.filename,
        media_body=media
    )
    # Execute request - store file on GCS
    results = request.execute()
    return_json = json.dumps(results, ensure_ascii=False)
    return return_json

参考URL

参考にしたホムペはもちろんあるのですが、日が空いてしまって、どこだかわからず…
もしもわかったら追記します。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?