使用s3-boto中断浏览器缓存的django-storage

Nun*_*147 5 django django-storage

我有一个django项目,它使用django-storage而不是s3-boto.

问题是位于S3上的每个文件都无法缓存,因为每个调用都更改了URL.

这里是django-storage生成的两个调用:

https://my.s3.amazonaws.com/cache/user_6/profile_pic/profile_profile_picture_thumbnail.jpg?Signature=HlVSayUIJj6dMyk%2F4KBtFlz0uJs%3D&Expires=1364418058&AWSAccessKeyId=[awsaccesskey]     
https://my.s3.amazonaws.com/cache/user_6/profile_pic/profile_profile_picture_thumbnail.jpg?Signature=xh2VxKys0pkq7yHpbJmH000wkwg%3D&Expires=1364418110&AWSAccessKeyId=[awsaccesskey]
Run Code Online (Sandbox Code Playgroud)

如您所见,签名是不同的.我该怎么办才不会破坏我的浏览器缓存?

Aar*_*ron 9

AWS_QUERYSTRING_AUTH = True(这是默认情况)时,每次我们获取 url 时,django 都会生成一个临时 url

如果您不想生成临时网址:

添加AWS_QUERYSTRING_AUTH = False到您的settings.py

如果您仍然想要一个临时网址:

临时 URL 的有效期为AWS_QUERYSTRING_EXPIRE几秒(默认为 3600 秒)。因此我们可以缓存这个临时 url(只要我们缓存的时间不超过它的有效时间)。这样,我们就可以为后续页面请求返回相同的 url,从而允许客户端浏览器从其缓存中获取数据。

设置.py

# We subclass the default storage engine to add some caching
DEFAULT_FILE_STORAGE = 'project.storage.CachedS3Boto3Storage'
Run Code Online (Sandbox Code Playgroud)

项目/存储.py

import hashlib

from django.conf import settings
from django.core.cache import cache
from storages.backends.s3boto3 import S3Boto3Storage

class CachedS3Boto3Storage(S3Boto3Storage):
    """ adds caching for temporary urls """

    def url(self, name):
        # Add a prefix to avoid conflicts with any other apps
        key = hashlib.md5(f"CachedS3Boto3Storage_{name}".encode()).hexdigest()
        result = cache.get(key)
        if result:
            return result

        # No cached value exists, follow the usual logic
        result = super(CachedS3Boto3Storage, self).url(name)

        # Cache the result for 3/4 of the temp_url's lifetime.
        try:
            timeout = settings.AWS_QUERYSTRING_EXPIRE
        except:
            timeout = 3600
        timeout = int(timeout*.75)
        cache.set(key, result, timeout)

        return result
Run Code Online (Sandbox Code Playgroud)


Dee*_*ash 8

在您的设置中,只需添加以下内容:

AWS_QUERYSTRING_AUTH = False
Run Code Online (Sandbox Code Playgroud)

这将确保生成文件的URL而不使用额外的参数.您的网址如下所示:

https://my.s3.amazonaws.com/cache/user_6/profile_pic/profile_profile_picture_thumbnail.jpg
Run Code Online (Sandbox Code Playgroud)