Upload to Google Cloud Storage using Django-storages

Umesh Saruk
2 min readJun 6, 2019

--

Recently I have implemented Google Cloud Storage using Django and found some issues mentioned below:

  1. Google Cloud Storage's default backend configuration is not a plug and play settings.
  2. Google Cloud backend’s def url(self, name) method calls Google’s APIs doing unnecessary HTTP calls to Google
  3. Returns a signed URL for the Blob and DOES NOT check for the existence of Blob which makes codes too slow for many use cases.

I wanted to access the GCP bucket and make it as the default storage location for uploading and sending the path to the function used in the views.py

To achieve this we need to use some additional configuration to implement Google Cloud Storage using Django.

Prequistives packages to install:

pip install google-cloud-storage==1.10.0  pip install django-storages==1.7.1

GOOGLE_APPLICATION_CREDENTIALS

Setup the environment variable called: GOOGLE_APPLICATION_CREDENTIALS. You should be able to download it (.json file) from your gcloud console. More info: https://cloud.google.com/docs/authentication/production#setting_the_environment_variable

Now here comes the twist, here you will need to create a new file called gcloud.py(you can name anything) next to settings.py. In this file, we override GoogleCloudStorage class for STATIC and MEDIA files.

gcloud.py

Once you set up the environment variable and glcoud.py, here is the configuration you will need to do in settings file with respect to the environment you are in. We need to change DEFAULT_FILE_STORAGE and STATICFILES_STORAGE to the new classes we created in gcloud.py

settings.py

That's all we need to configure to make Google Cloud Storage a default storage. Happy uploading!

References:

https://django-storages.readthedocs.io/en/latest/backends/gcloud.html

--

--