from flask import Flask, request, render_template_string, jsonify from google.cloud import storage import os import tempfile app = Flask(__name__) # Google Cloud Storageにアップロードする関数 def upload_to_gcs(bucket_name, file_path, destination_blob_name): # 匿名クライアントの作成 storage_client = storage.Client.create_anonymous_client() # バケットとブロブの取得 bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) # ファイルのアップロード blob.upload_from_filename(file_path) print(f"File {file_path} uploaded to {destination_blob_name}.") # アップロード後にキャッシュを削除 if os.path.exists(file_path): os.remove(file_path) # ファイルアップロードフォームを表示 @app.route('/', methods=['GET']) def index(): # HTMLフォームを直接Pythonの文字列として定義 upload_form_html = ''' ファイルアップロード

Google Cloud Storageへのファイルアップロード

''' return render_template_string(upload_form_html) # ファイルをアップロード処理する @app.route('/upload', methods=['POST']) def upload_file(): if 'file' not in request.files: return jsonify({'error': 'No file part'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'No selected file'}), 400 # 一時ファイルとして保存 with tempfile.NamedTemporaryFile(delete=False) as temp_file: temp_file.write(file.read()) temp_file.close() # GCSにアップロード upload_to_gcs('s4s-api-bucket', temp_file.name, file.filename) # 成功レスポンス return jsonify({'message': 'File successfully uploaded to GCS'}), 200 if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port=7860)