Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate signed url in Django Rest for a file in google cloud storage?

I am using Django Rest framework for making APIs. Along with it, I am using Google Cloud Storage to store media files. I have some questions in mind:

  1. How do I generate signed file urls using the django rest framework? I have been searching the net with same but not able to get clear picture of it. Link

  2. So, if I delete a file in database, will it be automatically deleted from Google cloud storage as well?

Thanks in advance!!!

like image 916
hardik24 Avatar asked Oct 11 '18 13:10

hardik24


1 Answers

How do I generate signed file urls using the django rest framework?

The django-storage module will take care of this for you automatically.

You can check it pretty easily, if you have uploaded an asset to your server, check the url at the FileField field of your model. (In my case it's called raw)

enter image description here

If you go to the right, you will see in the url the Signature parameter. If you reload the page, you'll see that the signature's value changes, proving you're actually using temporary signed urls.

Default expiration is 86400 seconds (1 day), you can change this with the GS_EXPIRATION variable.

So, if I delete a file in database, will it be automatically deleted from Google cloud storage as well?

Not by default, but you can add this functionnality easily by overriding your Model's delete method

class MyModel(models.Model):
    myfile = models.FileField(upload_to='filename/')

    def delete(self, *args, **kwargs):
        self.myfile.delete()
        super(MyModel, self).delete(*args, **kwargs)
like image 77
Overdrivr Avatar answered Oct 26 '22 03:10

Overdrivr