はじめに
PythonからGCSにアップロード・ダウンロードするためにはAPIキーが必要になるのでコンソールから予め取得しておいてください。

Google Cloud StorageをPythonから使う方法
今回はGoogle Cloud PlatformのCloud StorageをPythonから使う方法を紹介します。apiキーの作成はじめにapiにアクセスするためのキーファイルを生成します。GCPのコンソールにアクセスして「API...
Django
APIキーを用意できたら適当にプロジェクト・アプリを作成してsetting.pyの設定も済ませておきます。
今回はURLを次のように設定します。
/upload/ /download/{filename}
コード
app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("upload/",views.upload)
path("download/<str:filename>",views.download)
]
app/views.py
from django.shortcuts import render,redirect
from google.oauth2 import service_account
from google.cloud import storage
service_account_info = {
#APIキーの中身
}
def view(request):
if (request.method == "GET"):
return render(request,"app/upload.html")
else:
file = request.FILES["file"]
bucket = client.get_bucket("バケット名")
blob = bucket.blob("ファイル名")
blob.upload_from_file(file)
return redirect("/download/"+file.name)
def download(request,filename):
bucket = client.get_bucket("バケット名")
blob = bucket.blob(filename)
file = blob.download_as_bytes()
response = HttpResponse(file,content_type='application/octet-stream')
response["Content-Disposition"] = "filename="+filename
return response
テンプレート
app/upload.html
<form action="upload" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<button type="submit">アップロード</button>
</form>
ビスケットを送る0
コメント