我有两个数据库,希望每个数据库都有一个缓存表:
DATABASE1: web
CACHE TABLE: web_cache
DATABASE2: services
CACHE TABLE: services_cache
在我的项目中,我经常在两个数据库之间切换。我正在使用django缓存api,并且需要在必要时能够切换到services_cache表,例如,如果在服务数据库中注册了一个应用程序。问题是app_name在路由过程中始终显示为django_cache,这没有提供有关从何处调用.set()缓存的有意义的信息。
这是我的CacheRouter:
class CacheRouter:
"""A router to control all database cache operations"""
service_apps_r = ('services_cache', 'schema_manager')
def db_for_read(self, model, **hints):
"""Send all read operations on the services apps to the services DB, else go to the default db"""
if model._meta.app_label in self.service_apps_r:
return 'services'
return 'default'
def db_for_write(self, model, **hints):
"All cache write operations go to primary"
if model._meta.app_label == 'django_cache':
# if calling app is schema_manager <----- How can I achieve this?
return 'services'
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 == 'services'
return None
例如,在调用django缓存api的应用程序为schema_manager的情况下,我找不到任何有关设置提示的有用信息,从而无法重定向到服务缓存。
Django缓存:https://docs.djangoproject.com/en/2.1/topics/cache/
我对SO和django文档有很好的了解,但似乎在这里找不到解决方法。