Skip to content

Commit

Permalink
πŸ› Support aioredis from redis package (#369)
Browse files Browse the repository at this point in the history
πŸ›  Support `aioredis` from redis package
  • Loading branch information
yezz123 committed Feb 17, 2023
2 parents 7e8249b + 7854434 commit 8961f8e
Show file tree
Hide file tree
Showing 9 changed files with 42 additions and 22 deletions.
12 changes: 8 additions & 4 deletions authx/cache/redis.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
from typing import Iterable, Optional, Union

import redis
from redis import asyncio as aioredis


class RedisBackend:
"""Setup the Redis connection for the backend using redis"""
"""
Setup the Redis connection for the backend using aioredis.
_redis: Optional[redis.Redis] = None
"""

def set_client(self, redis: redis.Redis) -> None:
_redis: Optional[aioredis.Redis] = None

def set_client(self, redis: aioredis.Redis) -> None:
self._redis = redis

async def get(self, key: str) -> str:
Expand Down Expand Up @@ -36,5 +39,6 @@ async def incr(self, key: str) -> str:
return await self._redis.incr(key)

async def dispatch_action(self, channel: str, action: str, payload: dict) -> None:
# TODO: is publish_json exist in redis-py?
await self._redis.publish_json(channel, {"action": action, "payload": payload})
return None
6 changes: 3 additions & 3 deletions authx/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Iterable, Optional

import redis
from fastapi import APIRouter, HTTPException, Request
from redis import asyncio as aioredis

from authx.backend import UsersRepo
from authx.cache import RedisBackend
Expand Down Expand Up @@ -43,7 +43,7 @@ def __init__(
refresh_expiration,
)

def set_cache(self, client: redis.Redis) -> None:
def set_cache(self, client: aioredis.Redis) -> None:
self._cache_backend.set_client(client)

async def get_user(self, request: Request) -> User:
Expand Down Expand Up @@ -194,5 +194,5 @@ def admin_router(self) -> APIRouter:
def search_router(self) -> APIRouter:
return get_search_router(self._users_repo, self.admin_required)

def set_cache(self, cache_client: redis.Redis) -> None:
def set_cache(self, cache_client: aioredis.Redis) -> None:
self._cache_backend.set_client(cache_client)
2 changes: 1 addition & 1 deletion docs/configuration/cache/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ of the Redis class and pass it to the `set_redis` method.

```python
from authx import authx, RedisBackend
from redis import Redis
from redis import asyncio as Redis

auth = authx()

Expand Down
3 changes: 3 additions & 0 deletions scripts/clean.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ rm -f `find . -type f -name '.*~' `
rm -f `find . -type f -name .coverage`
rm -f `find . -type f -name ".coverage.*"`
rm -rf `find . -name __pycache__`
rm -rf `find . -name authx_profiling_results.html`
rm -rf `find . -name authx_profiling_results.json`
rm -rf `find . -name users.db`
rm -rf `find . -type d -name '*.egg-info' `
rm -rf `find . -type d -name 'pip-wheel-metadata' `
rm -rf `find . -type d -name .pytest_cache`
Expand Down
19 changes: 19 additions & 0 deletions scripts/docker.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash

set -e
set -x

echo "ENV=${ENV}"
echo "REDIS_URL-${REDIS_URL}"

export PYTHONPATH=.

# run redis container
docker run -d -p 6379:6379 --name redis redis

# run tests
pytest --cov=authx --cov=tests -xv

# Shutdown and remove redis container
docker stop redis
docker rm redis
12 changes: 3 additions & 9 deletions tests/cache/test_cache_config.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,12 @@
import random
import unittest
from datetime import timedelta
from unittest import mock

from authx.cache.config import basicConfig, config


@unittest.skip(
"Improve this test later while getting issues after adding the container of Redis to Github Workflow"
)
@mock.patch("authx.cache.config.uuid4")
def testConfig(mock_uuid4):
config.genSessionId()
mock_uuid4.assert_called_once_with() # pragma: no cover
def test_config() -> None:
session_id = config.genSessionId().isnumeric()
assert session_id is not None


def testBasicConfig():
Expand Down
4 changes: 2 additions & 2 deletions tests/cache/test_http_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

from authx import HTTPCache, cache, invalidate_cache

REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/3")
redis_client = redis.Redis.from_url(REDIS_URL)
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/2")
redis_client = redis.from_url(REDIS_URL)


class User:
Expand Down
2 changes: 1 addition & 1 deletion tests/middleware/test_middleware_Oauth2.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def setUpClass(cls):
cls.client = TestClient(app)

def test_redirects(self):
response = self.client.get("/", allow_redirects=False)
response = self.client.get("/", follow_redirects=False)

self.assertEqual(302, response.status_code)
url = URL(response.headers["Location"])
Expand Down
4 changes: 2 additions & 2 deletions tests/routers/test_routers_social.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_login(provider: str):
f"authx.routers.social.SocialService.login_{provider}",
mock.Mock(return_value="/"),
) as mock_method:
response = test_client.get(url, allow_redirects=False)
response = test_client.get(url, follow_redirects=False)
mock_method.assert_called_once()

assert response.status_code == 307
Expand Down Expand Up @@ -78,7 +78,7 @@ def test_callback(provider: str):
)
mock_resolve_user = patcher_resolve_user.start()
url = app.url_path_for("social:callback", provider=provider)
response = test_client.get(url, allow_redirects=False)
response = test_client.get(url, follow_redirects=False)

assert response.status_code == 307

Expand Down

0 comments on commit 8961f8e

Please sign in to comment.