From: Michael Tremer Date: Fri, 11 Aug 2023 14:49:58 +0000 (+0000) Subject: cache: Tidy up code X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=bac2e40bc777794f040526ee6a0ee75faa437a4b;p=pbs.git cache: Tidy up code Signed-off-by: Michael Tremer --- diff --git a/src/buildservice/cache.py b/src/buildservice/cache.py index a59b9af8..19f35de5 100644 --- a/src/buildservice/cache.py +++ b/src/buildservice/cache.py @@ -1,9 +1,7 @@ #!/usr/bin/python3 import asyncio -import datetime import logging -import pickle import redis.asyncio from .decorators import * @@ -20,7 +18,7 @@ class Cache(object): # Create a connection pool self.pool = redis.asyncio.connection.ConnectionPool.from_url( - "redis://localhost:6379/0", + "redis://localhost:6379/0", decode_responses=True, ) async def connection(self, *args, **kwargs): @@ -71,57 +69,46 @@ class Cache(object): # Return the connection back into the pool asyncio.run_coroutine_threadsafe(conn.close(), loop) - async def get(self, key): - """ - Fetches the value of a cached key - """ + async def _run(self, command, *args, **kwargs): + # Fetch our connection conn = await self.connection() - value = await conn.get(key) + # Get the function + func = getattr(conn, command) - # Nothing found - if not value: - return + # Call the function + return await func(*args, **kwargs) - # Decode pickled value - try: - return pickle.loads(value) - - # If the value could not be decoded, we return nothing making it look like - # no value was found in the cache. - except pickle.UnpicklingError: - return + async def get(self, key): + """ + Fetches the value of a cached key + """ + return await self._run("get", *args, **kwargs) - async def set(self, key, value, expires=None): + async def set(self, *args, **kwargs): """ Puts something into the cache """ - conn = await self.connection() - - # Figure out when this expires - if expires and isinstance(expires, datetime.timedelta): - expires = expires.total_seconds() + return await self._run("set", *args, **kwargs) - # Pickle value - value = pickle.dumps(value) - - # Send to redis - return await conn.set(key, value, ex=expires) - - async def delete(self, key): + async def delete(self, *args, **kwargs): """ Deletes the key from the cache """ - conn = await self.connection() - - return await conn.delete(key) + return await self._run("delete", *args, **kwargs) async def transaction(self, *args, **kwargs): + """ + Returns a new transaction + """ conn = await self.connection() return await conn.transaction(*args, **kwargs) async def pipeline(self, *args, **kwargs): + """ + Returns a new pipeline + """ conn = await self.connection() return conn.pipeline(*args, **kwargs)