Vit Amin
Vit Amin

Reputation: 683

Django 2: upload media to Google Cloud Storage with google-cloud-storage

I want to deploy Django app on Google Cloud (Google AppEngine and Cloud Sql). SO I need to store media files in Google CLoud Storage.

I found this code in google docs:

from google.cloud import storage
client = storage.Client()
# https://console.cloud.google.com/storage/browser/[bucket-id]/
bucket = client.get_bucket('bucket-id-here')
# Then do other things...
blob = bucket.get_blob('remote/path/to/file.txt')
print(blob.download_as_string())
blob.upload_from_string('New contents!')
blob2 = bucket.blob('remote/path/storage.txt')
blob2.upload_from_filename(filename='/local/path.txt')

I think I can use this in the views (for a FileField and an ImageField). But what should I do in my Django settings with MEDIA_ROOT in this case?

Upvotes: 1

Views: 3676

Answers (2)

Vit Amin
Vit Amin

Reputation: 683

It works in this way:

views.py

from google.cloud import storage

def your_view(self, request):
    #some your code
    client = storage.Client()
    bucket = client.get_bucket(settings.GOOGLE_CLOUD_STORAGE_BUCKET)
    #path to the cloud storage "directory"
    prefix = 'media/'
    delimiter = '/'
    blobs = client.list_blobs(
        bucket,
        prefix = prefix,
        delimiter = delimiter
    )
    blob = storage.blob.Blob(
        name = name,
        bucket = bucket)
    blob.upload_from_string(
        resized_image, #some data
        content_type = 'image/jpeg'
    )
    # other your code

settings.py

MEDIA_URL = 'https://storage.googleapis.com/YOUR_BUCKET/media/'
GOOGLE_CLOUD_STORAGE_BUCKET = 'YOUR_BUCKET'

Upvotes: 0

Joss Baron
Joss Baron

Reputation: 1524

You might take a look into this answers. Also whats comments @Oluwafemi Sule is true. On the other hand here you can find an example with python. Maybe you want to do some examples to clarify the usage, just have in mind that as this is a third party tool,Google cannot vouch for its accuracy.

Upvotes: 1

Related Questions