FastAPI: add redis integration

This includes the addition of the python-fakeredis package,
used for stubbing python-redis when a user does not have a
configured cache.

Signed-off-by: Kevin Morris <kevr@0cost.org>
This commit is contained in:
Kevin Morris 2021-06-28 08:49:02 -07:00
parent 96d1af9363
commit 91e769f603
No known key found for this signature in database
GPG key ID: F7E46DED420788F3
7 changed files with 123 additions and 3 deletions

57
aurweb/redis.py Normal file
View file

@ -0,0 +1,57 @@
import logging
import fakeredis
from redis import ConnectionPool, Redis
import aurweb.config
logger = logging.getLogger(__name__)
pool = None
class FakeConnectionPool:
""" A fake ConnectionPool class which holds an internal reference
to a fakeredis handle.
We normally deal with Redis by keeping its ConnectionPool globally
referenced so we can persist connection state through different calls
to redis_connection(), and since FakeRedis does not offer a ConnectionPool,
we craft one up here to hang onto the same handle instance as long as the
same instance is alive; this allows us to use a similar flow from the
redis_connection() user's perspective.
"""
def __init__(self):
self.handle = fakeredis.FakeStrictRedis()
def disconnect(self):
pass
def redis_connection(): # pragma: no cover
global pool
disabled = aurweb.config.get("options", "cache") != "redis"
# If we haven't initialized redis yet, construct a pool.
if disabled:
logger.debug("Initializing fake Redis instance.")
if pool is None:
pool = FakeConnectionPool()
return pool.handle
else:
logger.debug("Initializing real Redis instance.")
if pool is None:
redis_addr = aurweb.config.get("options", "redis_address")
pool = ConnectionPool.from_url(redis_addr)
# Create a connection to the pool.
return Redis(connection_pool=pool)
def kill_redis():
global pool
if pool:
pool.disconnect()
pool = None