# 缓存后端抽象
from django.core.cache import caches
from abc import ABC, abstractmethod


class CacheLayer(ABC):
    """统一缓存操作接口"""

    @abstractmethod
    def get(self, key: str, default=None):
        ...

    @abstractmethod
    def set(self, key: str, value, timeout: int):
        ...

    @abstractmethod
    def delete(self, key: str):
        ...

    @classmethod
    def create(cls, alias: str) -> 'CacheLayer':
        return DjangoAdapter(alias)


class DjangoAdapter(CacheLayer):
    """适配所有Django原生缓存后端"""

    def __init__(self, alias: str):
        self.backend = caches[alias]

    def get(self, key: str, default=None):
        return self.backend.get(key, default)

    def set(self, key: str, value, timeout: int):
        return self.backend.set(key, value, timeout)

    def delete(self, key: str):
        return self.backend.delete(key)
