Skip to content

Commit 983fa5c

Browse files
authored
Use shared Redis cache for jhu data (#306)
* add & log a data_id string for each cache * dev mode should run with debug log level * log missing country code at sub debug level * use pydantic for config managment * add redis config settings * add aiocache with redis support * use memory cache * use shared cache for jhu data * cleanup * fix url type * add aiofiles * add async save/read * update tests * update dependencies * change pylint config to pyproject.toml * cache jhu data (locally) for 30 minutes
1 parent 9e8d12b commit 983fa5c

File tree

16 files changed

+380
-714
lines changed

16 files changed

+380
-714
lines changed

.env.example

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
# Port to serve app on.
2-
PORT = 5000
2+
PORT = 5000
3+
LOCAL_REDIS_URL = redis://localhost:6379

Pipfile

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,17 @@ pytest-cov = "*"
2020
responses = "*"
2121

2222
[packages]
23+
aiocache = {extras = ["redis"],version = "*"}
24+
aiofiles = "*"
2325
aiohttp = "*"
2426
asyncache = "*"
2527
cachetools = "*"
2628
dataclasses = {version = "*",markers = "python_version<'3.7'"}
2729
fastapi = "*"
2830
gunicorn = "*"
2931
idna_ssl = {version = "*",markers = "python_version<'3.7'"}
32+
pydantic = {extras = ["dotenv"],version = "*"}
3033
python-dateutil = "*"
31-
python-dotenv = "*"
3234
requests = "*"
3335
uvicorn = "*"
3436

Pipfile.lock

Lines changed: 119 additions & 45 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

app/caches.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""app.caches.py"""
2+
import functools
3+
import logging
4+
from typing import Union
5+
6+
import aiocache
7+
8+
from .config import get_settings
9+
10+
LOGGER = logging.getLogger(name="app.caches")
11+
12+
SETTINGS = get_settings()
13+
14+
if SETTINGS.rediscloud_url:
15+
REDIS_URL = SETTINGS.rediscloud_url
16+
LOGGER.info("Using Rediscloud")
17+
else:
18+
REDIS_URL = SETTINGS.local_redis_url
19+
LOGGER.info("Using Local Redis")
20+
21+
22+
@functools.lru_cache()
23+
def get_cache(namespace) -> Union[aiocache.RedisCache, aiocache.SimpleMemoryCache]:
24+
"""Retunr """
25+
if REDIS_URL:
26+
LOGGER.info("using RedisCache")
27+
return aiocache.RedisCache(
28+
endpoint=REDIS_URL.host,
29+
port=REDIS_URL.port,
30+
password=REDIS_URL.password,
31+
namespace=namespace,
32+
create_connection_timeout=5,
33+
)
34+
LOGGER.info("using SimpleMemoryCache")
35+
return aiocache.SimpleMemoryCache(namespace=namespace)
36+
37+
38+
async def check_cache(data_id: str, namespace: str = None):
39+
"""Check the data of a cache given an id."""
40+
cache = get_cache(namespace)
41+
result = await cache.get(data_id, None)
42+
LOGGER.info(f"{data_id} cache pulled")
43+
await cache.close()
44+
return result
45+
46+
47+
async def load_cache(data_id: str, data, namespace: str = None, cache_life: int = 3600):
48+
"""Load data into the cache."""
49+
cache = get_cache(namespace)
50+
await cache.set(data_id, data, ttl=cache_life)
51+
LOGGER.info(f"{data_id} cache loaded")
52+
await cache.close()

app/config.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""app.config.py"""
2+
import functools
3+
import logging
4+
5+
from pydantic import AnyUrl, BaseSettings
6+
7+
CFG_LOGGER = logging.getLogger("app.config")
8+
9+
10+
class _Settings(BaseSettings):
11+
port: int = 5000
12+
rediscloud_url: AnyUrl = None
13+
local_redis_url: AnyUrl = None
14+
15+
16+
@functools.lru_cache()
17+
def get_settings(**kwargs) -> BaseSettings:
18+
"""
19+
Read settings from the environment or `.env` file.
20+
https://pydantic-docs.helpmanual.io/usage/settings/#dotenv-env-support
21+
22+
Usage:
23+
import app.config
24+
25+
settings = app.config.get_settings(_env_file="")
26+
port_number = settings.port
27+
"""
28+
CFG_LOGGER.info("Loading Config settings from Environment ...")
29+
return _Settings(**kwargs)

app/config/__init__.py

Whitespace-only changes.

app/config/settings.py

Lines changed: 0 additions & 10 deletions
This file was deleted.

0 commit comments

Comments
 (0)