配置
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'def_cache_table',
},
'apps': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'app_cache_table',
},
}
注意 必须有defaut
创建表
manage.py createcachetable
shell运行
>>> from django.core.cache import caches
>>> dc = caches['default']
>>> dc.set('keydef', 'valdef')
>>> dc.get('keydef')
'valdef'
>>> ac = caches['apps']
>>> ac.set('keyapp', 'valapp')
>>> ac.get('keyapp')
'valapp'
>>> from django.core.cache import cache
>>> cache.get('keydef')
'valdef
sqlite> .tables
app_cache_table def_cache_table my_cache_table
sqlite> select * from def_cache_table
...> ;
:1:keydef|gASVCgAAAAAAAACMBnZhbGRlZpQu|2016-04-20 12:46:08
sqlite> select * from app_cache_table;
:1:keyapp|gASVCgAAAAAAAACMBnZhbGFwcJQu|2016-04-20 12:46:52
sqlite>
multiple db
添加了一个mysql数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'mysql':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myproject',
'USER': 'root',
'PASSWORD': '111111',
},
}
myproject 库需要事先创建好, 然后创建表
manage.py createcachetable --database mysql
mysql> USE MYPROJECT;
Database changed
mysql> SHOW TABLES;
Empty set (0.00 sec)
mysql> SHOW TABLES;
+---------------------+
| Tables_in_myproject |
+---------------------+
| app_cache_table |
| def_cache_table |
+---------------------+
2 rows in set (0.00 sec)
db router设置
http://www.laonan.net/blog/zxg4Aj2hEeSGQv79rf__Vw/
https://docs.djangoproject.com/en/1.9/topics/db/multi-db/
Settings.py中设置 db router 位置
Settings.py所在的文件夹内创建一个conf文件夹 内创建cache_router.py
DATABASE_ROUTERS = ['untitled.conf.cache_router.CacheRouter']
cache_router.py 类似下面的形式 注意 文件位置和名字可任意
class CacheRouter(object):
"""A router to control all database cache operations"""
def db_for_read(self, model, **hints):
"All cache read operations go to the replica"
if model._meta.app_label == 'django_cache':
return 'cache_replica'
return None
def db_for_write(self, model, **hints):
"All cache write operations go to primary"
if model._meta.app_label == 'django_cache':
return 'cache_primary'
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"Only install the cache model on primary"
if app_label == 'django_cache':
return db == 'cache_primary'
return None