开发者

Django cache separate database

开发者 https://www.devze.com 2023-03-27 20:54 出处:网络
My django project is using separate database and that database has to be cached by using django cache. So the way is not straight forward.

My django project is using separate database and that database has to be cached by using django cache. So the way is not straight forward.

I read in djangoproject but I could not understand. The link shows a model "CacheRouter" with some defs.

I am not sure whether it is sample code or

  • the code already present somewhere or
  • the code I have to alter or
  • the code I have to add in开发者_开发知识库 my models.

Can anyone explain elaborately ?


You can do a generic router, which is configured using a dict of the apps that go to a non-default database.

app_to_database = {
    'django_cache': 'the_declared_name_of_the_cache_database',
}

class CacheRouter(object):

    def db_for_read(self, model, **hints):
        return app_to_database.get(model._meta.app_label, None)

    def db_for_write(self, model, **hints):
        return app_to_database.get(model._meta.app_label, None)

    def allow_syncdb(self, db, model):
        _db = app_to_database.get(model._meta.app_label, None)
        return db == _db if _db else None

Edit: better explanation

If you want to use different schemas, or database servers or even differnet backends altogether, you need to declare them in settings.py:

DATABASES = {
    'default': # the one storing your app data
        { 'NAME': 'main_db', # this is the schema name
          'USER': '...',
          'PASSWORD': '...',
          'ENGINE': '...', # etc...
        },
    'the_declared_name_of_the_cache_database': # the name is arbitrary here
        { 'NAME': 'db_for_djcache', # this is the schema name
          'USER': '...',
          'PASSWORD': '...',
          'ENGINE': '...', # etc...
        },
}

DATABASE_ROUTERS = ['path.to.MyAppRouter'] # that is, the module.ClassName of the
                                           # router class you defined above.

If, on the other side, as you seem to imply from your comment, you only need a different table (inside the same schema), you don't need a router at all, everything is managed smoothly by django.

You can check what happens using any GUI client to the database. Just open your schema(ta) and check the tables and their content.

0

精彩评论

暂无评论...
验证码 换一张
取 消