68
Itβs bad practice to put code in settings.py
other than assignments. Itβs better suited as a management command:
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')
Which you can add to your project by sticking it in someapp/management/commands
. For instance you could create a new app called utils
and add that to your INSTALLED_APPS
and the directory structure would look like this:
utils
βββ __init__.py
βββ management
βββ __init__.py
βββ commands
βββ __init__.py
βββ clearcache.py
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:
alias runserver='./manage.py clearcache && ./manage.py runserver'
Alternately I think you can write it as a stand-alone script and 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()
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.
16
Django Extensions lets you wipe cache via
manage.py clear_cache
more info and many further commands in their docs.
- [Django]-ERROR: Could not build wheels for backports.zoneinfo, which is required to install pyproject.toml-based projects
- [Django]-Django ORM and locking table
- [Django]-Case insensitive urls for Django?
3
You typically only 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/stable/ref/settings/#std:setting-CACHES-VERSION)
- [Django]-Django: reverse accessors for foreign keys clashing
- [Django]-How to start doing TDD in a django project?
- [Django]-Command not found: django-admin.py
1
How about this? Define a boolean value in settings.py
, for example CLEAR_CACHE_ON_RESTART = True
and then check in other place if it is True
. If it is, then clear cache and set it to False
. This code can be placed in any view (like a main view) and probably even in manage.py
or urls.py
(although I didnβt check this and it doesnβt look too good). Give it a try!
- [Django]-Comma separated lists in django templates
- [Django]-How to test custom django-admin commands
- [Django]-Bypass confirmation prompt for pip uninstall
0
If you have multiple cache backends, django.core.cache.cache.clear()
will only clear the default cache. To make sure your clear_cache
command clears cache from all your backends, you should use the following command:
from django.conf import settings
from django.core.cache import caches
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Clear cache"
def handle(self, **options):
for k in settings.CACHES.keys():
caches[k].clear()
self.stdout.write("Cleared cache '{}'.\n".format(k))
- [Django]-Django-rest-framework http put failing with 415 on django 1.5
- [Django]-Django set field value after a form is initialized
- [Django]-PyCharm hangs on 'scanning files to index' background task