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

Add support for caching Pydantic models #65

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion src/fastapi_redis_cache/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)}
Expand Down
7 changes: 7 additions & 0 deletions tests/main.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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):
Expand Down
5 changes: 5 additions & 0 deletions tests/pydantic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from pydantic import BaseModel


class SampleModel(BaseModel):
key: str
9 changes: 9 additions & 0 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down