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:
JavaScript
x
5
1
from django.core.files.storage import default_storage
2
file = default_storage.open(filename, 'w')
3
file.write('testing'')
4
file.close()
5
Advertisement
Answer
JavaScript
1
35
35
1
import base64
2
import random
3
import string
4
import os
5
6
letters = string.ascii_lowercase
7
random_string = ''.join(random.choice(letters) for i in range(10))
8
9
env = os.environ.get("_ENVIROMENT", "development")
10
filename = f'test_upload_file_{env}_{random_string}.txt'
11
encoded_text = 'S2FtaWwgd2FzIGhlcmU='
12
13
decoded_plaintext = base64.b64decode(encoded_text)
14
15
# Perform upload to the default GS_BUCKET_NAME location
16
# from django.core.files.storage import default_storage
17
# file = default_storage.open(filename, 'w')
18
# file.write(decoded_plaintext)
19
# file.close()
20
21
f = open(filename, "wb")
22
f.write(decoded_plaintext)
23
f.close()
24
25
from google.cloud import storage
26
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", None)
27
bucket_name = os.environ.get("GS_BUCKET_NAME_FILE_UPLOADS", None)
28
client = storage.Client(project=project_id)
29
bucket = client.get_bucket(bucket_name)
30
31
filename_on_gcp = filename
32
blob = bucket.blob(filename_on_gcp)
33
with open(filename, "rb") as my_file:
34
blob.upload_from_file(my_file)
35