django static files versioning

后端 未结 10 1056
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 21:26

I\'m working on some universal solution for problem with static files and updates in it.

Example: let\'s say there was site with /static/styles.css file - a

10条回答
  •  情歌与酒
    2021-01-30 21:56

    There is an update for @deathangel908 code. Now it works well with S3 storage also (and with any other storage I think). The difference is using of static file storage for getting file content. Original doesn't work on S3.

    appname/templatetags/md5url.py:

    import hashlib
    import threading
    from django import template
    from django.conf import settings
    from django.contrib.staticfiles.storage import staticfiles_storage
    
    register = template.Library()
    
    
    class UrlCache(object):
        _md5_sum = {}
        _lock = threading.Lock()
    
        @classmethod
        def get_md5(cls, file):
            try:
                return cls._md5_sum[file]
            except KeyError:
                with cls._lock:
                    try:
                        md5 = cls.calc_md5(file)[:8]
                        value = '%s%s?v=%s' % (settings.STATIC_URL, file, md5)
                    except OSError:
                        value = settings.STATIC_URL + file
                    cls._md5_sum[file] = value
                    return value
    
        @classmethod
        def calc_md5(cls, file_path):
            with staticfiles_storage.open(file_path, 'rb') as fh:
                m = hashlib.md5()
                while True:
                    data = fh.read(8192)
                    if not data:
                        break
                    m.update(data)
                return m.hexdigest()
    
    
    @register.simple_tag
    def md5url(model_object):
        return UrlCache.get_md5(model_object)
    

提交回复
热议问题