3

I am working on a project that requires load media files from Google Cloud CDN. Currently, I am loading the files in the form of urls - cdn.mydomain.com/image.jpg . But this requires to provide public access to the object. I need to generate signed url for secure access of these resources. I have checked django-storages. It provides signed url straight from the storage bucket but does not say anything about signed urls for CDN. How do I generate signed urls for Google Cloud CDN inside django and keep using the django-storages library?

alamshafi2263
  • 639
  • 4
  • 15

2 Answers2

4

I ended up writing a storage backend. The settings.CUSTOM_DOMAIN is the address of the CDN. My backend code is as follows -

class CustomGoogleCloudStorage(GoogleCloudStorage):
    custom_domain = settings.CUSTOM_DOMAIN

    def make_url(self, name):
        host = "https://" + self.custom_domain
        return urllib.parse.urljoin(host, name)

    def url(self, name):
        name = self._normalize_name(name)
        url = self.make_url(name)
        key_name, base64_key = get_storage_key()
        expiration_time = datetime.datetime.utcnow() + datetime.timedelta(hours=1) #put your desired time here
        return sign_url(url, key_name, base64_key, expiration_time)

The sign_url function is taken from GCP's github.

alamshafi2263
  • 639
  • 4
  • 15
2

Django is a high-level Python Web framework. You might use the Cryptographic signing feature used by Django with the signed URLs Python (Programmatically creating signed URLs) described in Cloud CDN documentation. Take a look on both links and let us know if that helps to answer your inquiry.