我想在每次重启/重装django服务器时刷新memcached.我使用cherrypy进行生产和内置服务器进行开发.
我会在CACHES之后将其添加到settings.py:
from django.core.cache import cache cache.clear()
但它会进行递归导入:
Error: Can't find the file 'settings.py' in the directory containing 'manage.py'. It appears you've customized things. You'll have to run django-admin.py, passing it your settings module. (If the file settings.py does indeed exist, it's causing an ImportError somehow.) make: *** [server] Error 1
还有其他建议吗?谢谢.
将代码放在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'
或者我认为您可以将其编写为独立脚本并手动配置其所需的设置:
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只会导入一次,所以一般情况下我都会避免这种情况.如果信号框架可以在每次启动应用程序时触发一次事件,在为这样的东西加载设置之后,这将是很好的.
Django Extensions允许您通过以下方式清除缓存
manage.py clear_cache
在他们的文档中有更多信息和许多其他命令。