Django中如何配置Database缓存?

maiziedu · · 2714 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

  BACKEND:   django.core.cache.backends.db.DatabaseCache   LOCATION:   数据库表名   示例:   CACHES = {   'default': {   'BACKEND': 'django.core.cache.backends.db.DatabaseCache',   'LOCATION': 'my_cache_table',   }   }   Database缓存配置——创建缓存表   使用数据库缓存之前,需要创建缓存表:   python manage.py createcachetable   创建的表名为缓存配置中的LOCATION值   思考:Cache表创建到哪里去了呢?   配置好数据库缓存之前还需要配置数据库   示例:   DATABASES = {   'default': {   'NAME': 'app_data',   'ENGINE': 'django.db.backends.postgresql_psycopg2',   'USER': 'postgres_user',   'PASSWORD': ’’password   }   }   只会创建不存在的表,如果表已经存在,不操作 默认情况下会将cache表创建到default数据库,如果要创建到其他数据库,需要指定database   疑问?   1)可否将cache分类存储到不同的表?   2)可否将cache分别存储到不同数据库?   答案:可以的   1)Mutiple Database Caches: createcachetable会为每个 Cache 创建一张缓存表   2)Mutiple Databases: createcachetable会去查找数据库routers中的allow_migrate()方法,检查是否允许migrate。   3)createcachetable默认使用default数据库,要使用其它数据库,需要用--database参数。   Multi Database Caches配置示例   CACHES = {   ’default': {   'BACKEND': 'django.core.cache.backends.db.DatabaseCache',   'LOCATION': ’api_cache_table',   },# 必须配置default   ‘apps’: {   'BACKEND': 'django.core.cache.backends.db.DatabaseCache',   'LOCATION': ’apps_cache_table',   }   }   如果要使用缓存,必须配置default缓存,这里的示例又配置了apps这个缓存   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"   …   def db_for_write(self, model, **hints):   "All cache write operations go to primary"   …   def allow_migrate(self, db, app_label, model_name=None, **hints):   "Only install the cache model on primary"   …   dbRouter控制缓存的读写,需要分别实现db_for_read,db_for_write和allow_migrate这三个方法   1.Multiple Databases——读   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   所有DB缓存的读操作指向 cache_replica DB   2.Multiple Databases——写   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   所有DB缓存的写操作指向 cache_primary DB   3.Multiple Databases——migration   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   允许在 cache_primary DB 上执行 migration   原文链接:http://www.maiziedu.com/wiki/django/database/

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2714 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传