I want memcached to be flushed on every restart/reload of django server. I use cherrypy for production and builtin server for development.
I would add this to settings.py, right after CACHES:
from django.core.cache import cache
cache.clear()
but it makes a recursive import:
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
Any other suggestions? Thanks.
How about this? Define a boolean value in
settings.py
, for exampleCLEAR_CACHE_ON_RESTART = True
and then check in other place if it isTrue
. If it is, then clear cache and set it toFalse
. This code can be placed in any view (like a main view) and probably even inmanage.py
orurls.py
(although I didn't check this and it doesn't look too good). Give it a try!Django Extensions lets you wipe cache via
more info and many further commands in their docs.
It's bad practice to put code in
settings.py
other than assignments. It's better suited as a management command:Which you can add to your project by sticking it in
someapp/management/commands
. For instance you could create a new app calledutils
and add that to yourINSTALLED_APPS
and the directory structure would look like this:You can now clear cache by doing
./manage.py clearcache
. If you want to run clearcache every time you runserver you can just write a shell alias to do that:Alternately I think you can write it as a stand-alone script and configure the settings it requires by hand:
Writing your stand-alone script like this will prevent circular imports, and allow you to import it from your settings.py. Although there is no guarantee that settings.py will be imported only once, so in general I'd avoid this. It'd be nice if the signal framework could fire off an event once every time the app is started, after settings are loaded for stuff like this.
You typically wan't to invalidate your caches if the code changes in a way that requires a new cache. Not on every restart.
This is best handled by using the Django feature:
settings.CACHES.VERSION
[1], and increase that number every time you change the code that changes the format of cached data. That way, on a deploy, you automatically will use a fresh cache when you deploy new code, but keep the cache if you're code is cache-compatible with the previous code.[1] (https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-CACHES-VERSION)