django缓存优化 Database 缓存解析

配置

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 端

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






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值