这是indexloc提供的服务,不要输入任何密码
Skip to content

Add Django Cache Backend #153

@epicserve

Description

@epicserve

Is there a reason this library doesn't have a Django Cache Backend? I just wrote one, which seems generic enough to be added.

We need it because we have multiple web processes running behind a load balancer, and changing an environment variable that is used from the Django settings works. However, if we need to toggle the state, we have to reload the app, and under AWS ECS/Fargate, it takes about five minutes. This cache backend will allow us to toggle the state instantly instead of waiting five minutes for the app to reload.

Thoughts?

import logging

from django.core.cache import cache
from maintenance_mode.backends import AbstractStateBackend
from redis.exceptions import ConnectionError


logger = logging.getLogger(__name__)


class MaintenanceModeCacheBackend(AbstractStateBackend):
    def get_value(self):
        try:
            value = cache.get("maintenance_mode")
        except ConnectionError:
            logger.warning("Unable to connect to Django's cache backend. Maintenance mode is automatically set to on.")
            value = "1"
        self.from_bool_to_str_value(value)
        return value

    def set_value(self, value):
        # Using the following will cast the value to '0' when turning off maintenance mode, which causes it to not be
        # turned off. Leaving the line for reference as to why it was removed.
        # value = self.from_bool_to_str_value(value)
        try:
            cache.set("maintenance_mode", value, None)
        except ConnectionError:
            pass

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions