- Django 3 Web Development Cookbook
- Aidas Bendoraitis Jake Kronika
- 275字
- 2025-04-04 13:15:07
There's more...
This method works only if each of your environments contains the full Git repository of the project—in some cases, for example, when you use Heroku or Docker for deployments—you don't have access to a Git repository and the git log command in the remote servers. In order to have the STATIC_URL with a dynamic fragment, you have to read the timestamp from a text file—for example, myproject/settings/last-modified.txt—that should be updated with each commit.
In this case, your settings would contain the following lines:
# settings/_base.py
with open(os.path.join(BASE_DIR, 'myproject', 'settings', 'last-update.txt'), 'r') as f:
timestamp = f.readline().strip()
STATIC_URL = f'/static/{timestamp}/'
You can make your Git repository update last-modified.txt with a pre-commit hook. This is an executable bash script that should be called pre-commit and placed under django-myproject/.git/hooks/:
# django-myproject/.git/hooks/pre-commit
#!/usr/bin/env python
from subprocess import check_output, CalledProcessError
import os
from datetime import datetime
def root():
''' returns the absolute path of the repository root '''
try:
base = check_output(['git', 'rev-parse', '--show-toplevel'])
except CalledProcessError:
raise IOError('Current working directory is not a git repository')
return base.decode('utf-8').strip()
def abspath(relpath):
''' returns the absolute path for a path given relative to the root of
the git repository
'''
return os.path.join(root(), relpath)
def add_to_git(file_path):
''' adds a file to git '''
try:
base = check_output(['git', 'add', file_path])
except CalledProcessError:
raise IOError('Current working directory is not a git repository')
return base.decode('utf-8').strip()
def main():
file_path = abspath("myproject/settings/last-update.txt")
with open(file_path, 'w') as f:
f.write(datetime.now().strftime("%Y%m%d%H%M%S"))
add_to_git(file_path)
if __name__ == '__main__':
main()
This script will update last-modified.txt whenever you commit to the Git repository and will add that file to the Git index.