diff --git a/src/fastapi_redis_cache/util.py b/src/fastapi_redis_cache/util.py index 663bf3c..9696a4c 100644 --- a/src/fastapi_redis_cache/util.py +++ b/src/fastapi_redis_cache/util.py @@ -3,6 +3,7 @@ from decimal import Decimal from dateutil import parser +from pydantic import BaseModel DATETIME_AWARE = "%m/%d/%Y %I:%M:%S %p %z" DATE_ONLY = "%m/%d/%Y" @@ -22,7 +23,9 @@ class BetterJsonEncoder(json.JSONEncoder): def default(self, obj): - if isinstance(obj, datetime): + if isinstance(obj, BaseModel): + return json.loads(obj.json()) + elif isinstance(obj, datetime): return {"val": obj.strftime(DATETIME_AWARE), "_spec_type": str(datetime)} elif isinstance(obj, date): return {"val": obj.strftime(DATE_ONLY), "_spec_type": str(date)} diff --git a/tests/main.py b/tests/main.py index be2b693..2522494 100644 --- a/tests/main.py +++ b/tests/main.py @@ -1,6 +1,7 @@ import logging from datetime import date, datetime, timedelta from decimal import Decimal +from .pydantic import SampleModel from fastapi import FastAPI, Request, Response @@ -32,6 +33,12 @@ def cache_json_encoder(): } +@app.get("/cache_pydantic") +@cache() +def cache_json_list(): + return SampleModel(key="it works!") + + @app.get("/cache_one_hour") @cache_one_hour() def partial_cache_one_hour(response: Response): diff --git a/tests/pydantic.py b/tests/pydantic.py new file mode 100644 index 0000000..0b96e8d --- /dev/null +++ b/tests/pydantic.py @@ -0,0 +1,5 @@ +from pydantic import BaseModel + + +class SampleModel(BaseModel): + key: str diff --git a/tests/test_cache.py b/tests/test_cache.py index bdc0ccb..15733bf 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -123,6 +123,15 @@ def test_cache_json_encoder(): assert json_dict["final_calc"] == Decimal(3.14) +def test_cache_pydantic(): + response = client.get("/cache_pydantic") + assert response.status_code == 200 + response_json = response.json() + assert response_json == { + "key": "it works!" + } + + def test_cache_control_no_cache(): # Simple test that verifies if a request is recieved with the cache-control header field containing "no-cache", # no caching behavior is performed