#!/usr/bin/python3
import asyncio
-import datetime
import logging
-import pickle
import redis.asyncio
from .decorators import *
# 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):
# 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)