Skip to content

Commit

Permalink
Moved common backend __ini__ logic to BaseCache
Browse files Browse the repository at this point in the history
  • Loading branch information
argaen committed Oct 11, 2016
1 parent cb3565a commit 133ac74
Show file tree
Hide file tree
Showing 12 changed files with 34 additions and 36 deletions.
17 changes: 15 additions & 2 deletions aiocache/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,22 @@

class BaseCache(metaclass=abc.ABCMeta):
"""
Base class that agregates the common logic for the different caches that may exist
Base class that agregates the common logic for the different caches that may exist. Available
options are:
:param serializer: obj with :class:`aiocache.serializers.BaseSerializer` interface.
Must implement ``loads`` and ``dumps`` methods.
:param namespace: string to use as prefix for the key used in all operations of the backend.
:param max_keys: int indicating the max number of keys to store in the backend. If not
specified or 0, it's unlimited.
"""

def __init__(self, serializer=None, namespace=None, max_keys=None):

self.serializer = serializer or self.get_serializer()
self.namespace = namespace or ""
self.max_keys = max_keys or None

def get_serializer(self):
return DefaultSerializer()

Expand Down Expand Up @@ -50,5 +63,5 @@ async def persist(self, key): # pragma: no cover

def _build_key(self, key):
if self.namespace:
return "{}:{}".format(self.namespace, key)
return "{}{}".format(self.namespace, key)
return key
4 changes: 0 additions & 4 deletions aiocache/backends/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ class SimpleMemoryCache(BaseCache):

_cache = {}

def __init__(self, namespace=None, serializer=None):
self.serializer = serializer or self.get_serializer()
self.namespace = namespace or ""

async def get(self, key, default=None, loads_fn=None):
"""
Get a value from the cache. Returns default if not found.
Expand Down
5 changes: 2 additions & 3 deletions aiocache/backends/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@

class RedisCache(BaseCache):

def __init__(self, endpoint=None, port=None, namespace=None, serializer=None, loop=None):
def __init__(self, endpoint=None, port=None, loop=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.endpoint = endpoint or "127.0.0.1"
self.port = port or 6379
self.serializer = serializer or self.get_serializer()
self.namespace = namespace or ""
self._pool = None
self._loop = loop or asyncio.get_event_loop()

Expand Down
5 changes: 5 additions & 0 deletions docs/backends.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ Now let's go with a more specific case. Let's pick Redis as the backend with nam
#. "key" will become "test:key" when applying the ``build_key``
#. "value" will become an array of bytes when calling ``serializer.serialize``

BaseCache
---------

.. autoclass:: aiocache.backends.base.BaseCache
:members:

RedisCache
----------
Expand Down
9 changes: 0 additions & 9 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,6 @@
# documentation.
#
# html_theme_options = {}
html_theme_options = {
'github_user': 'argaen',
'github_repo': 'aiocache',
'github_button': True,
'github_type': 'star',
'github_banner': True,
'travis_button': True,
'codecov_button': True,
}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
Expand Down
19 changes: 6 additions & 13 deletions docs/decorators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,14 @@ Decorators

aiocache comes with a couple of decorators for caching results from asynchronous functions. Do not use the decorator in synchronous functions, it may lead to unexpected behavior.

Decorators can be used with any backend/serializer available. With that, you are able to store any python object into the desired backend:

.. literalinclude:: ../examples/decorator.py
:language: python
:linenos:

As you may have imagined, it's very annoying to specify the backend, serializer, port and so everytime you decorate a function. For that, the ``aiocache.config_default_cache()`` utility is provided. This function will configure a global cache that will fallback any of the attributes that are not passed in the decorators. Also, you'll be able to use this default cache explicitly accessing ``aiocache.default_cache``:

.. literalinclude:: ../examples/config_default_cache.py
:language: python
:linenos:


cached
---------------------

.. automodule:: aiocache
:members: cached

The decorator can be used with any backend/serializer available. With that, you are able to store any python object into the desired backend:

.. literalinclude:: ../examples/decorator.py
:language: python
:linenos:
2 changes: 1 addition & 1 deletion examples/python_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


async def main():
cache = RedisCache(serializer=PickleSerializer(), namespace="default")
cache = RedisCache(serializer=PickleSerializer(), namespace="default:")
# This will serialize to pickle and store in redis with bytes format
await cache.set("key", MyObject(x=1, y=2))
# This will retrieve the object and deserialize back to MyObject
Expand Down
2 changes: 1 addition & 1 deletion examples/serializer_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def loads(self, value):


async def main():
cache = RedisCache(serializer=MySerializer(), namespace="main")
cache = RedisCache(serializer=MySerializer(), namespace="main:")
await cache.set("key", "value") # Will use MySerializer.dumps method
print(await cache.get("key")) # Will use MySerializer.loads method

Expand Down
2 changes: 1 addition & 1 deletion examples/serializer_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def loads(value):


async def main():
cache = RedisCache(namespace="main")
cache = RedisCache(namespace="main:")
await cache.set("key", MyType(1, 2), dumps_fn=dumps)
print(await cache.get("key", loads_fn=loads))

Expand Down
2 changes: 1 addition & 1 deletion examples/simple_redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


async def main():
cache = RedisCache(endpoint="127.0.0.1", port=6379, namespace="default")
cache = RedisCache(endpoint="127.0.0.1", port=6379, namespace="default:")
await cache.set("key", "value")
await cache.set("expire_me", "value", ttl=10) # Key will expire after 10 secs
print(await cache.get("key"))
Expand Down
2 changes: 1 addition & 1 deletion requirements-ci.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ pytest-asyncio==0.5.0
pytest-cov==2.3.1
pytest-mock==1.2
codecov==2.0.5
sphinx==1.4.7
sphinx==1.4.6
marshmallow==2.10.2
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sphinx-autobuild==0.6.0

0 comments on commit 133ac74

Please sign in to comment.