django static files versioning

后端 未结 10 1082
伪装坚强ぢ
伪装坚强ぢ 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:50

    Simple templatetag vstatic that creates versioned static files urls that extends Django's behaviour:

    from django.conf import settings
    from django.contrib.staticfiles.templatetags.staticfiles import static
    
    @register.simple_tag
    def vstatic(path):
        url = static(path)
        static_version = getattr(settings, 'STATIC_VERSION', '')
        if static_version:
             url += '?v=' + static_version
        return url
    

    If you want to automatically set STATIC_VERSION to the current git commit hash, you can use the following snippet (Python3 code adjust if necessary):

    import subprocess
    
    
    def get_current_commit_hash():
        try:
            return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode('utf-8')
        except:
            return ''
    

    At settings.py call get_current_commit_hash(), so this will be calculated only once:

    STATIC_VERSION = get_current_commit_hash()
    

提交回复
热议问题