Skip to content

Commit

Permalink
Deprecate settings module (#215)
Browse files Browse the repository at this point in the history
  • Loading branch information
argaen authored May 7, 2017
1 parent fa10818 commit 8ccae99
Show file tree
Hide file tree
Showing 9 changed files with 139 additions and 83 deletions.
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ You can also setup cache aliases like in Django settings:
import asyncio
from aiocache import settings, caches, SimpleMemoryCache, RedisCache
from aiocache import caches, SimpleMemoryCache, RedisCache
from aiocache.serializers import DefaultSerializer, PickleSerializer
# You can use either classes or strings for referencing classes
settings.set_config({
caches.set_config({
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
Expand Down
2 changes: 1 addition & 1 deletion aiocache/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from .log import logger
from .settings import settings
from .backends.memory import SimpleMemoryCache
from .factory import caches
from .settings import settings
from .decorators import cached, multi_cached
from ._version import __version__

Expand Down
88 changes: 74 additions & 14 deletions aiocache/factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from copy import deepcopy

from aiocache.settings import settings


def _class_from_string(class_path):
class_name = class_path.split('.')[-1]
Expand Down Expand Up @@ -33,34 +31,96 @@ def _create_cache(cache, serializer=None, plugins=None, **kwargs):

class CacheHandler:

_config = {
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
}
}

def __init__(self):
self._caches = {}

@classmethod
def _get_alias_config(cls, alias):
config = settings.get_config()
if alias not in config:
raise KeyError(
"Could not find config for '{}' in settings, ensure you called settings.from_config"
" specifying the config for that cache".format(alias))

return config[alias]

def get(self, alias):
try:
return self._caches[alias]
except KeyError:
pass

config = self._get_alias_config(alias)
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
return cache

def create(self, alias, **kwargs):
config = self._get_alias_config(alias)
config = self.get_alias_config(alias)
cache = _create_cache(**{**config, **kwargs})
return cache

def get_alias_config(self, alias):
config = self.get_config()
if alias not in config:
raise KeyError(
"Could not find config for '{0}', ensure you include {0} when calling"
"caches.set_config specifying the config for that cache".format(alias))

return config[alias]

def get_config(self):
"""
Return copy of current stored config
"""
return deepcopy(self._config)

def set_config(self, config):
"""
Set (override) the default config for cache aliases from a dict-like structure.
The structure is the following::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
}
'default' key must always exist when passing a new config. Default configuration
is::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
}
}
You can set your own classes there.
The class params accept both str and class types.
All keys in the config are optional, if they are not passed the defaults
for the specified class will be used.
"""
if "default" not in config:
raise ValueError("default config must be provided")
self._config = config


caches = CacheHandler()
60 changes: 8 additions & 52 deletions aiocache/settings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from copy import deepcopy
from aiocache import caches
from aiocache.log import logger


class settings:
Expand All @@ -20,60 +21,15 @@ def __new__(cls):

@classmethod
def get_alias(cls, alias):
return cls._config[alias]
logger.warning("Deprecated, please use 'aiocache.caches.get_config[alias]'")
return caches.get_alias_config(alias)

@classmethod
def get_config(cls):
"""
Return copy of current stored config
"""
return deepcopy(cls._config)
logger.warning("Deprecated, please use 'aiocache.caches.get_config'")
return caches.get_config()

@classmethod
def set_config(cls, config):
"""
Set (override) the default settings for aiocache from a dict-like structure.
The structure is the following::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
}
'default' key must always exist when passing a new config. Default configuration
is::
{
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
}
}
You can set your own classes there.
The class params accept both str and class types.
All keys in the config are optional, if they are not passed the defaults
for the specified class will be used.
"""
if "default" not in config:
raise ValueError("default config must be provided")
cls._config = config
logger.warning("Deprecated, please use 'aiocache.caches.get_config'")
return caches.set_config(config)
6 changes: 3 additions & 3 deletions docs/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ Configuration
Cache aliases
-------------

The settings module allows to setup cache configurations and then use them with the specified alias. To set the config, call ``settings.set_config``:
The caches module allows to setup cache configurations and then use them with the specified alias. To set the config, call ``caches.set_config``:

.. automethod:: aiocache.settings.set_config
.. automethod:: aiocache.caches.set_config

To retrieve a copy of the current config, you can use ``settings.get_config``.
To retrieve a copy of the current config, you can use ``caches.get_config``.


Next snippet shows an example usage:
Expand Down
4 changes: 2 additions & 2 deletions examples/cached_alias_config.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import asyncio

from aiocache import settings, caches, SimpleMemoryCache, RedisCache
from aiocache import caches, SimpleMemoryCache, RedisCache
from aiocache.serializers import DefaultSerializer, PickleSerializer

settings.set_config({
caches.set_config({
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
Expand Down
3 changes: 2 additions & 1 deletion examples/lru_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ async def redis():
assert await cache.get("key") is None
assert await cache.get("key_1") == "value"
assert await cache.get("key_2") == "value"
assert len(await cache.raw("keys", "*")) == 2
keys = await cache.raw("keys", "*")
assert len(keys) == 2


def test_redis():
Expand Down
6 changes: 3 additions & 3 deletions tests/ut/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import asynctest

from aiocache.base import BaseCache
from aiocache import settings, RedisCache, MemcachedCache
from aiocache import caches, RedisCache, MemcachedCache
from aiocache.plugins import BasePlugin
from aiocache.serializers import DefaultSerializer

Expand All @@ -15,8 +15,8 @@ def pytest_namespace():


@pytest.fixture(autouse=True)
def reset_settings():
settings.set_config({
def reset_caches():
caches.set_config({
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
Expand Down
49 changes: 44 additions & 5 deletions tests/ut/test_factory.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import pytest

from aiocache import SimpleMemoryCache, RedisCache, settings, caches
from aiocache import SimpleMemoryCache, RedisCache, caches
from aiocache.factory import _class_from_string, _create_cache
from aiocache.serializers import PickleSerializer
from aiocache.plugins import TimingPlugin
Expand Down Expand Up @@ -48,7 +48,7 @@ def test_create_not_reuse(self):
assert caches.create('default') is not caches.create('default')

def test_create_extra_args(self):
settings.set_config({
caches.set_config({
'default': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.9",
Expand All @@ -62,7 +62,7 @@ def test_create_extra_args(self):
assert cache.db == 10

def test_retrieve_cache(self):
settings.set_config({
caches.set_config({
'default': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
Expand All @@ -85,7 +85,7 @@ def test_retrieve_cache(self):
assert len(cache.plugins) == 2

def test_retrieve_cache_new_instance(self):
settings.set_config({
caches.set_config({
'default': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
Expand All @@ -108,7 +108,7 @@ def test_retrieve_cache_new_instance(self):
assert len(cache.plugins) == 2

def test_multiple_caches(self):
settings.set_config({
caches.set_config({
'default': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
Expand Down Expand Up @@ -136,3 +136,42 @@ def test_multiple_caches(self):
assert len(default.plugins) == 2

assert isinstance(alt, SimpleMemoryCache)

def test_default_caches(self):
assert caches.get_config() == {
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
}
}

def test_get_alias_config(self):
assert caches.get_alias_config("default") == {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.DefaultSerializer"
}
}

def test_set_empty_config(self):
with pytest.raises(ValueError):
caches.set_config({})

def test_set_config_no_default(self):
with pytest.raises(ValueError):
caches.set_config({
'no_default': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.10",
'port': 6378,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
})

0 comments on commit 8ccae99

Please sign in to comment.