2023-01-12 01:04:47 +00:00
|
|
|
# SPDX-FileCopyrightText: 2015 Eric Larson
|
|
|
|
#
|
|
|
|
# SPDX-License-Identifier: Apache-2.0
|
2023-09-17 19:22:54 +00:00
|
|
|
from __future__ import annotations
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
from datetime import datetime, timezone
|
|
|
|
from typing import TYPE_CHECKING
|
|
|
|
|
2023-01-12 01:04:47 +00:00
|
|
|
from cachecontrol.cache import BaseCache
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
if TYPE_CHECKING:
|
|
|
|
from redis import Redis
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
class RedisCache(BaseCache):
|
|
|
|
def __init__(self, conn: Redis[bytes]) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
self.conn = conn
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
def get(self, key: str) -> bytes | None:
|
2023-01-12 01:04:47 +00:00
|
|
|
return self.conn.get(key)
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
def set(
|
|
|
|
self, key: str, value: bytes, expires: int | datetime | None = None
|
|
|
|
) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
if not expires:
|
|
|
|
self.conn.set(key, value)
|
2023-01-06 11:47:44 +00:00
|
|
|
elif isinstance(expires, datetime):
|
2023-09-17 19:22:54 +00:00
|
|
|
now_utc = datetime.now(timezone.utc)
|
|
|
|
if expires.tzinfo is None:
|
|
|
|
now_utc = now_utc.replace(tzinfo=None)
|
|
|
|
delta = expires - now_utc
|
|
|
|
self.conn.setex(key, int(delta.total_seconds()), value)
|
2023-01-06 11:47:44 +00:00
|
|
|
else:
|
|
|
|
self.conn.setex(key, expires, value)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
def delete(self, key: str) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
self.conn.delete(key)
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
def clear(self) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
"""Helper for clearing all the keys in a database. Use with
|
|
|
|
caution!"""
|
|
|
|
for key in self.conn.keys():
|
|
|
|
self.conn.delete(key)
|
|
|
|
|
2023-09-17 19:22:54 +00:00
|
|
|
def close(self) -> None:
|
2023-01-12 01:04:47 +00:00
|
|
|
"""Redis uses connection pooling, no need to close the connection."""
|
|
|
|
pass
|