Google Cloud Storage vs Google Cloud CDN

To answer your question of how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage on your django. You can base your implementation below with django-storages

Google Cloud Storage vs Google Cloud CDN

To answer your question of how can I use the Google Cloud CDN on top of my current implementation with Google Cloud Storage on your django. You can base your implementation below with django-storages

requirements.txt (the versions are the latest up to this day: 05-31-2020)

...
django-storages==1.19.1
google-cloud-storage==1.28.1

example/example/settings.py

...
...
SB_SA_FILE = os.environ.get('STORAGE_BUCKETS_FILE',
                            'storageBucketsBackendServiceKey.json')
STATICFILES_STORAGE = 'example.lib.storages.GoogleStaticFilesStorage'  # static
DEFAULT_FILE_STORAGE = 'example.lib.storages.GoogleMediaFilesStorage'  # media
GS_AUTO_CREATE_BUCKET = True
GS_DEFAULT_ACL = 'publicRead'
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    f'/usr/src/app/{SB_SA_FILE}'
)
GS_BUCKET_NAME = os.environ.get('GS_BUCKET_NAME')
CDN_HOSTNAME = os.environ.get('CDN_HOSTNAME', '')

example/example/lib/storages.py

from django.conf import settings
from storages.backends.gcloud import GoogleCloudStorage



class GoogleMediaFilesStorage(GoogleCloudStorage):

    def _save(self, name, content):
        name = f'{settings.MEDIA_URL[1:]}{name}'
        return super()._save(name, content)

    def url(self, name):
        """
        @brief      for implementation of CDN using image field url
        @return     Dynamic return of CDN or local URL
        """
        if settings.CDN_HOSTNAME:
            url = f'{settings.CDN_HOSTNAME}/{name}'
            return url
        return super().url(name)


class GoogleStaticFilesStorage(GoogleCloudStorage):
    def url(self, name):
        name = f'static/{name}'
        if settings.CDN_HOSTNAME:
            url = f'{settings.CDN_HOSTNAME}/{name}'
            return url
        return super().url(name)

Lastly, you need to run your django application with a CDN_HOSTNAME environment variable. The value of CDN_HOSTNAME environment variable must be the domain mapped in your Google Cloud Global Load Balancer which your desired Cloud Storage is set as a backend bucket