Reputation: 3400
I'm using gcloud wrapped into django-storages logic. I have never feed the service with a url path of my bucket: only provided DEFAULT_FILE_STORAGE and GS_BUCKET_NAME which are the name of my glcoud project and storage.
My question is: How can I get the full url of my images? My images are saved with a relative url, which make sens into the DB. But I can't found any right documentation about how you can get the base url of the django.core.files.storage collection of object storage.
Some filestorage objects ask a valid relative image url in order to retrieve the full path. But this is not what I want: I just want to know (programatically) the base url of my (only one) bucket. The template {% image item.image %}
is able to generate the full url, but from the code side view it seems totally obscure for me.
Any help or advice?
Upvotes: 1
Views: 5621
Reputation: 77251
It is easier to get the full URL than get the prefix and join the relative part of the URL that is stored by some endpoints.
The base class for Django file storage backend is Storage. This class has an url
method that is likely to be implemented in any cloud storage backend worth its salary:
url(name)
Returns the URL where the contents of the file referenced by name can be accessed. For storage systems that don’t support access by URL this will raise NotImplementedError instead.
So just serialize the result of this method in your API. For example if you have your model already serialized as a dict named "data" you can update the "image" field from relative to absolute using:
relative_url = data.get("image")
full_url = relative_url and default_storage.url(relative_url)
data.update({"image": full_url})
Upvotes: 7