将代码放在settings.py 中而不是赋值是不好的做法。它更适合作为管理命令:
from django.core.management.base import BaseCommand
from django.core.cache import cache
class Command(BaseCommand):
def handle(self, *args, **kwargs):
cache.clear()
self.stdout.write('Cleared cache\n')
您可以通过将其粘贴到 someapp/management/commands 中来添加到您的项目中。例如,您可以创建一个名为utils 的新应用程序并将其添加到您的INSTALLED_APPS,目录结构将如下所示:
utils
├── __init__.py
└── management
├── __init__.py
└── commands
├── __init__.py
└── clearcache.py
您现在可以通过./manage.py clearcache 清除缓存。如果你想在每次运行服务器时都运行 clearcache,你可以写一个 shell 别名来做到这一点:
alias runserver='./manage.py clearcache && ./manage.py runserver'
或者,我认为您可以将其编写为独立脚本和configure the settings it requires by hand:
from django.conf import settings
# obviously change CACHES to your settings
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'unique-snowflake'
}
}
settings.configure(CACHES=CACHES) # include any other settings you might need
from django.core.cache import cache
cache.clear()
像这样编写您的独立脚本将防止循环导入,并允许您从 settings.py 中导入它。虽然不能保证 settings.py 只会被导入一次,但总的来说我会避免这种情况。如果信号框架可以在每次启动应用程序时触发一次事件,在为此类内容加载设置之后,那就太好了。