soiz1 commited on
Commit
8ab1d78
·
verified ·
1 Parent(s): 3bca415

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, render_template_string, jsonify
2
+ from google.cloud import storage
3
+ import os
4
+ import tempfile
5
+
6
+ app = Flask(__name__)
7
+
8
+ # Google Cloud Storageにアップロードする関数
9
+ def upload_to_gcs(bucket_name, file_path, destination_blob_name):
10
+ # 匿名クライアントの作成
11
+ storage_client = storage.Client.create_anonymous_client()
12
+
13
+ # バケットとブロブの取得
14
+ bucket = storage_client.bucket(bucket_name)
15
+ blob = bucket.blob(destination_blob_name)
16
+
17
+ # ファイルのアップロード
18
+ blob.upload_from_filename(file_path)
19
+ print(f"File {file_path} uploaded to {destination_blob_name}.")
20
+
21
+ # アップロード後にキャッシュを削除
22
+ if os.path.exists(file_path):
23
+ os.remove(file_path)
24
+
25
+ # ファイルアップロードフォームを表示
26
+ @app.route('/', methods=['GET'])
27
+ def index():
28
+ # HTMLフォームを直接Pythonの文字列として定義
29
+ upload_form_html = '''
30
+ <!DOCTYPE html>
31
+ <html lang="ja">
32
+ <head>
33
+ <meta charset="UTF-8">
34
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
35
+ <title>ファイルアップロード</title>
36
+ </head>
37
+ <body>
38
+ <h1>Google Cloud Storageへのファイルアップロード</h1>
39
+ <form action="/upload" method="post" enctype="multipart/form-data">
40
+ <label for="file">アップロードするファイルを選択:</label>
41
+ <input type="file" name="file" id="file" required>
42
+ <button type="submit">アップロード</button>
43
+ </form>
44
+ </body>
45
+ </html>
46
+ '''
47
+ return render_template_string(upload_form_html)
48
+
49
+ # ファイルをアップロード処理する
50
+ @app.route('/upload', methods=['POST'])
51
+ def upload_file():
52
+ if 'file' not in request.files:
53
+ return jsonify({'error': 'No file part'}), 400
54
+
55
+ file = request.files['file']
56
+ if file.filename == '':
57
+ return jsonify({'error': 'No selected file'}), 400
58
+
59
+ # 一時ファイルとして保存
60
+ with tempfile.NamedTemporaryFile(delete=False) as temp_file:
61
+ temp_file.write(file.read())
62
+ temp_file.close()
63
+
64
+ # GCSにアップロード
65
+ upload_to_gcs('your-bucket-name', temp_file.name, file.filename)
66
+
67
+ # 成功レスポンス
68
+ return jsonify({'message': 'File successfully uploaded to GCS'}), 200
69
+
70
+ if __name__ == '__main__':
71
+ app.run(debug=True)