Reputation: 15107
I'm able to upload a file in Google Storage but the problem is that it goes to the default bucket where my static files are: GS_BUCKET_NAME='static-files'
I'd like to continue uploading the static files to the 'static-files' bucket, but I would like to also upload the user files to a different bucket: 'user-upload-files'
How can I do this in Django 3.2.7, Python 3.9.7
For reference, right now I'm doing:
from django.core.files.storage import default_storage
file = default_storage.open(filename, 'w')
file.write('testing'')
file.close()
Upvotes: 0
Views: 241
Reputation: 15107
import base64
import random
import string
import os
letters = string.ascii_lowercase
random_string = ''.join(random.choice(letters) for i in range(10))
env = os.environ.get("_ENVIROMENT", "development")
filename = f'test_upload_file_{env}_{random_string}.txt'
encoded_text = 'S2FtaWwgd2FzIGhlcmU='
decoded_plaintext = base64.b64decode(encoded_text)
# Perform upload to the default GS_BUCKET_NAME location
# from django.core.files.storage import default_storage
# file = default_storage.open(filename, 'w')
# file.write(decoded_plaintext)
# file.close()
f = open(filename, "wb")
f.write(decoded_plaintext)
f.close()
from google.cloud import storage
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", None)
bucket_name = os.environ.get("GS_BUCKET_NAME_FILE_UPLOADS", None)
client = storage.Client(project=project_id)
bucket = client.get_bucket(bucket_name)
filename_on_gcp = filename
blob = bucket.blob(filename_on_gcp)
with open(filename, "rb") as my_file:
blob.upload_from_file(my_file)
Upvotes: 1