
上QQ阅读APP看书,第一时间看更新
How to do it...
The procedure to put the Git timestamp in the STATIC_URL setting consists of the following two steps:
- If you haven't done so yet, create the myproject.apps.core app in your Django project. You should also create a versioning.py file there:
# versioning.py
import subprocess
from datetime import datetime
def get_git_changeset_timestamp(absolute_path):
repo_dir = absolute_path
git_log = subprocess.Popen(
"git log --pretty=format:%ct --quiet -1 HEAD",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=repo_dir,
universal_newlines=True,
)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.utcfromtimestamp(int(timestamp))
except ValueError:
# Fallback to current timestamp
return datetime.now().strftime('%Y%m%d%H%M%S')
changeset_timestamp = timestamp.strftime('%Y%m%d%H%M%S')
return changeset_timestamp
- Import the newly created get_git_changeset_timestamp() function in the settings and use it for the STATIC_URL path, as follows:
# settings/_base.py
from myproject.apps.core.versioning import get_git_changeset_timestamp
# ...
timestamp = get_git_changeset_timestamp(BASE_DIR)
STATIC_URL = f'/static/{timestamp}/'