Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement cache protocol for redis client #7

Merged
merged 1 commit into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions fastapi_extras/databases/redis.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
from typing import AsyncGenerator, Union
from typing import Any, AsyncGenerator, Optional, Union

import redis.asyncio as redis
from pydantic import RedisDsn


class Redis(redis.Redis):
async def get(self, key: str, *args: Any, **kwargs: Any) -> Optional[str]:
return await super().get(key, *args, **kwargs)

async def set(
self, key: str, value: str, ttl: Optional[int] = None, *args: Any, **kwargs: Any
) -> None:
await super().set(key, value, ttl, *args, **kwargs)


class RedisManager:
def __init__(self, url: Union[RedisDsn, str]):
self.pool = redis.ConnectionPool.from_url(str(url))

async def __call__(self) -> AsyncGenerator[redis.Redis, None]:
cli = redis.Redis(connection_pool=self.pool)
async def __call__(self) -> AsyncGenerator[Redis, None]:
cli = Redis(connection_pool=self.pool)

try:
yield cli
Expand Down
25 changes: 18 additions & 7 deletions tests/databases/test_redis.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,35 @@
from typing import Union
from typing import Any, Optional

import pytest
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.testclient import TestClient
from pydantic import BaseModel
from pytest import MonkeyPatch
from redis.asyncio import Redis
from typing_extensions import Annotated

from fastapi_extras.databases.redis import RedisManager
from fastapi_extras.databases.redis import Redis, RedisManager


class FakeRedis:
db = {}
closed = []

async def get(self, key: str) -> Union[bytes, None]:
async def get(self, key: str) -> Optional[str]:
return FakeRedis.db.get(key)

async def set(self, key: str, val: str):
FakeRedis.db[key] = val.encode()
async def set(
self, key: str, val: str, ttl: Optional[int] = None, *args: Any, **kwargs: Any
) -> None:
FakeRedis.db[key] = val

async def aclose(self):
FakeRedis.closed.append(id(self))

@classmethod
def flush(cls):
cls.db.clear()
cls.closed.clear()


class Item(BaseModel):
key: str
Expand All @@ -36,7 +42,7 @@ class Item(BaseModel):

@app.get("/items/{key}", response_model=Item)
async def read(key: str, redis: Annotated[Redis, Depends(redis_manager)]):
item = await redis.get(key)
item = await redis.get(key) or ""

if not item:
HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Item not found")
Expand All @@ -60,6 +66,11 @@ def redis_mock(monkeypatch: MonkeyPatch):
monkeypatch.setattr("redis.asyncio.Redis.aclose", FakeRedis.aclose)


@pytest.fixture(autouse=True)
def redis_flush():
FakeRedis.flush()


def test_redis_manager():
data = [
{"key": "foo", "val": "bar"},
Expand Down