python - 重新启动 django 服务器时清除缓存的最佳位置

标签 python django memcached

我希望在 django 服务器每次重新启动/重新加载时刷新 memcached。我使用cherrypy进行生产,使用内置服务器进行开发。

我会将它添加到 settings.py 中,在 CACHES 之后:

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'

或者,我认为您可以将其编写为独立脚本和 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 只会被导入一次,但总的来说我会避免这种情况。如果信号框架可以在每次启动应用程序时触发一个事件,在为此类内容加载设置之后,那就太好了。

关于python - 重新启动 django 服务器时清除缓存的最佳位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5942759/

相关文章:

python - 使用和不使用 GPU 编程的语法差异?

python - 登录 Django 1.5

c - 对 `memcached_exist' 的 undefined reference

python - 定义 __getattribute__ 方法时发生“NoneType”对象不支持项目分配

python - 具有只读共享内存的 Python 中的多处理?

python - 我如何从这张图片中删除背景,只想从图片中选择生菜?

python - 单元测试通过了 Django 中模型的正则表达式验证器

python - 无法迁移以及如何使用 Django python 设置 mysql DB

javascript - 使用具有未定义的成功回调函数的 Bluebird

python - 获取 Django 中的缓存键列表