tsaebeht
tsaebeht

Reputation: 1680

How to set an AWS S3 object to never expire in Django Storages?

I am using django-storage (which uses Boto3 internally) to upload images. I am successfully able to do so and the return URL I get is of this format:

https://.s3.amazonaws.com/foo.jpg?Signature=&AWSAccessKeyId=&Expires=1513089114

where Signature and AWSAccessKeyId are filled in as well.

Now, I need to give this URL directly to Mobile Developers and I can't have the timeout set so late. I need it for many years or potentially always accessible. What is a good way to do so? What is the solution

Upvotes: 6

Views: 7676

Answers (4)

hannah
hannah

Reputation: 51

If your S3 bucket is public, you can use this setting to turn off query parameter authentication.

Setting AWS_QUERYSTRING_AUTH to False to remove query parameter authentication
from generated URLs. This can be useful if your S3 buckets are public.

Upvotes: 5

Bruno A.
Bruno A.

Reputation: 1875

The accepted answer achieved almost what I wanted. I didn't want to set it application wide, but only on a specific file. If you're like me, read on...

You can generate the expiration for a specific file field by using the storage's url() method which has an optional expire kwargs:

post = Post.objects.first()
post.image.storage.url(post.image.name, expire=60*60*24*365)

The downside of this is that it's incompatible with Django's default storage API, which would raise a TypeError locally:

TypeError: url() got an unexpected keyword argument 'expire'

Upvotes: 2

valex
valex

Reputation: 5809

Found better solution to make url for file in S3BotoStorage for 10 years available in Django FileField. In settings.py:

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' ...

And solution is:

from django.core.files.storage import default_storage
from myapp.models import MyModel

myobj = MyModel.objects.first()
key = default_storage.bucket.new_key(myobj.file_field.name)
url = key.generate_url(expires_in=60*60*24*365*10)

url will be valid for 10 years.

Upvotes: 1

gabbar0x
gabbar0x

Reputation: 4266

On glancing through the django-storages S3 Docs , I see there is a provision for

AWS_QUERYSTRING_EXPIRE which states

The number of seconds that a generated URL is valid for.

So if you wanted the link to be valid for 5 years from now, you can just add the corresponding number of seconds here which would amount to 157784630

So in conclusion, just add the following in your settings.py

AWS_QUERYSTRING_EXPIRE = '157784630'

This doesn't really seem like good practice to me but more like a convenient hack/workaround instead.

Upvotes: 11

Related Questions