Skip to content

Commit ff70de3

Browse files
authored
Merge pull request #18 from Kilo59/redis
Redis
2 parents c1e97e1 + c97476e commit ff70de3

File tree

12 files changed

+250
-93
lines changed

12 files changed

+250
-93
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: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,16 @@ pytest-cov = "*"
2020
responses = "*"
2121

2222
[packages]
23+
aiocache = {extras = ["redis"],version = "*"}
2324
aiohttp = "*"
2425
asyncache = "*"
2526
cachetools = "*"
2627
dataclasses = {version = "*",markers = "python_version<'3.7'"}
2728
fastapi = "*"
2829
gunicorn = "*"
2930
idna_ssl = {version = "*",markers = "python_version<'3.7'"}
31+
pydantic = {extras = ["dotenv"],version = "*"}
3032
python-dateutil = "*"
31-
python-dotenv = "*"
3233
requests = "*"
3334
uvicorn = "*"
3435

Pipfile.lock

Lines changed: 94 additions & 28 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, HttpUrl
6+
7+
CFG_LOGGER = logging.getLogger("app.config")
8+
9+
10+
class _Settings(BaseSettings):
11+
port: int = 5000
12+
rediscloud_url: HttpUrl = 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.

app/main.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
app.main.py
33
"""
44
import logging
5-
import os
65

76
import pydantic
87
import uvicorn
@@ -11,6 +10,7 @@
1110
from fastapi.middleware.gzip import GZipMiddleware
1211
from fastapi.responses import JSONResponse
1312

13+
from .config import get_settings
1414
from .data import data_source
1515
from .routers import V1, V2
1616
from .utils.httputils import setup_client_session, teardown_client_session
@@ -20,6 +20,8 @@
2020
# ############
2121
LOGGER = logging.getLogger("api")
2222

23+
SETTINGS = get_settings()
24+
2325
APP = FastAPI(
2426
title="Coronavirus Tracker",
2527
description=(
@@ -93,5 +95,5 @@ async def handle_validation_error(
9395
# Running of app.
9496
if __name__ == "__main__":
9597
uvicorn.run(
96-
"app.main:APP", host="127.0.0.1", port=int(os.getenv("PORT", "5000")), log_level="info",
98+
"app.main:APP", host="127.0.0.1", port=SETTINGS.port, log_level="info",
9799
)

0 commit comments

Comments
 (0)